Random string pattern generator in JavaScript

In this article I’m going to present a JavaScript code that generates a random string in a certain pattern. The JS function takes a string that matches the given pattern and returns a random string that contains the same type of characters in the same order as the sample.
random string generator js function

Example

InputAA aaa1111 ### Aaaaaa
Interpreted as: Two capital letters, one space, three lowercase letters, four numbers, three special characters and a capitalized six-letter word.
Example result that matches the pattern: XC tmr4990 %&@ Yvhwfd

I could have specified AB abc1234 !@# Abcdef for the input or any other string that matches the desired result.

The JavaScript Code

The function below distinguishes lower and capital letters, numbers and handles everything else as special characters but you can tweak the code to match your needs.

function randomStringPattern(input) {
  var text = "";
  var possible;
  for (var j = 0; j < input.length; j++) {
    if (input[j] == " ") {
        possible = ' ';
    } else if ((input[j] == input[j].toUpperCase()) && (input[j] != input[j].toLowerCase())) {
        possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    } else if ((input[j] == input[j].toLowerCase()) && (input[j] != input[j].toUpperCase())) {
        possible = "abcdefghijklmnopqrstuvwxyz";
    } else if ('0123456789'.indexOf(input[j]) !== -1) {
        possible = "0123456789";
    } else {
        possible = "#!@~$%^&*)-_"
    }
    text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
  return text;
}

Live Demo

The example below generates ten strings that match this pattern: AA aaa1111 ### Aaaaaa
Switch to the Result tab to see the output: