Search code examples
javascripthtmlalphanumeric

Generate password with alpha numeric characters in JavaScript


I want to generate a random password with Alpha numeric characters in it. I have written a function which returns a random password with Alpha-numeric characters. But i only want to add 4 alphanumeric characters from the provided string. Edited: I know this is not the best solution, but i have managed to get the desired output, If someone would like to get his hands on the code and optimize it, then it would be really helpful.

function getRandomPassword(length, numberOfNonAlphaNumericChars) {
const passwordDigit = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP1234567890";
const alphaNumericChar = "!@#$%^&*()_-+=[{]};:>|./?";
var temp1 = "";
var temp2 = "";
var pass = "";
if(length < 1 || length > 128) {
console.log("Number Exceeds");
}
if(numberOfNonAlphaNumericChars > length || numberOfNonAlphaNumericChars < 0) {
console.log("Error");
}
  for(var i = 0; i < length; i++) {
        var x = Math.floor(Math.random() * length);
    temp1 += passwordDigit.charAt(x);
    }
  for(var j = 0; j < numberOfNonAlphaNumericChars; j++) {
    var alphaNumericCharPos = Math.floor(Math.random() * numberOfNonAlphaNumericChars);
    temp2 += alphaNumericChar.charAt(alphaNumericCharPos);
  }
    
  var newPass = [temp1.slice(0, x), temp2, temp1.slice(x)].join('');
    
  console.log(newPass);
  return newPass;
}
getRandomPassword(16, 4);

jsfiddle: (https://jsfiddle.net/37rjgfad/11/)


Solution

  • This will get you exactly 4 non-alphanumeric characters:

    function jumble(str) {
      return [...str]
        .sort(() => Math.random() - 0.5)
        .join('')
    }
    
    // no change to this function
    function randomString(length, chars) {
        var mask = '';
        if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
        if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        if (chars.indexOf('#') > -1) mask += '0123456789';
        if (chars.indexOf('!') > -1) mask += '!@#$%^&*()_-+=[{]};:>|./?';
        var result = '';
        for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
        return result;
    }
    
    console.log(
      jumble(randomString(12, 'aA#') + randomString(4, '!'))
    )

    Modify as needed if you want a different distribution. For example:

    jumble(
      randomString(4, 'a')
      + randomString(4, 'A')
      + randomString(4, '!')
      + randomString(4, '#')
    )
    

    Would give you a 16-character string containing exactly 4 of each character type, or:

    jumble(randomString(12, '!') + randomString(4, 'aA#'))
    

    Would give you 12 non-alphanumerics and 4 alphanumerics.