How to generate Random Password with JavaScript

This cool snippet will generate a random string using JavaScript.

Among other things, it can be used to generate secure passwords.

JavaScript snippet


function GeneratePassword(lengthOfPassword) {
var theLetters = "abcdefghijklmnopqrstuvwxyz";
var StrongPasswordArray = [];
var capitalise;
for (var i = 0; i < lengthOfPassword; i++) { capitalise = Math.round(Math.random() * 1); if (capitalise === 0) { StrongPasswordArray[i] = theLetters.charAt(Math.round(Math.random() * 25)).toUpperCase(); } else { StrongPasswordArray[i] = theLetters.charAt(Math.round(Math.random() * 25)); } } var numberOfDigits; numberOfDigits = Math.round(Math.random() * (lengthOfPassword - 1)) + 1; var positionForNumeric, theNumber; for (i = 0; i < numberOfDigits; i++) { positionForNumeric = Math.round(Math.random() * (lengthOfPassword - 1)); theNumber = Math.round(Math.random() * 9); StrongPasswordArray[positionForNumeric] = theNumber; } return StrongPasswordArray; }

View Demo

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*