Tags

, , ,

I have written a small piece of code to generate a random password in JavaScript. This function is very good JavaScript Password Generator tool.

JavaScript Password Generator

//JavaScript Password Generator
function generatePassword(passwordLength, specialChars) {
  var iteration = 0;
  var password = "";
  var randomNumber;
  if(specialChars == undefined){
      var specialChars = false;
  }
  while(iteration < passwordLength){
    randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
    if(!specialChars){
      if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
      if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
      if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
      if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
    }
    iteration++;
    password += String.fromCharCode(randomNumber);
  }
  return password;
}

This function takes two parameters: integer value for password length and optional boolean value true if you want to include special characters in your generated passwords.

How to Use :

generatePassword(8);
// Output : ZMfBhjhM
Advertisements