How to generate Random Password with JavaScript

This cool snippet will generate a random string using JavaScript. My most used bookmark, probably. I use it constantly to create new accounts anywhere on the web. I have been increasing the length of the passwords over the years to make it even harder to crack.

The function accepts 1 parameter, the length of the string. Give it a try.

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;
	}	

Demo

View Demo

About Ricard Torres

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.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

Leave a Reply

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

*
*