Generate passwords with JavaScript


The function generatePassword() is a simple yet customizable function that generates a random password string, the default password length is 6, you can override it by calling the function like thisĀ  generatePassword(n) where n is the password length. The possible characters are defined within the function with the variable chars

The function: generatePassword([len=6])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function generatePassword(len){
	len	= parseInt(len);
	if(!len)
		len = 6;
	var password = "";
	var chars    = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var charsN   = chars.length;
	var nextChar;
 
	for(i=0; i<len; i++){
		nextChar = chars.charAt(Math.floor(Math.random()*charsN));
		password += nextChar;
	}
	return password;
}

Usage

The first example show the function without the optional len patamater(string length), and second example makes use of it:

1
2
3
4
5
6
// Example 1: No len
window.alert("A random string of 6 characters: " + generatePassword());
 
// Example 2: Using len
pwdLen = 10;
window.alert("A random string of " + pwdLen + "characters: " + generatePassword(pwdLen));

Try it

Generate a random password of 128 characters.

Further reading

Related links

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy this password:

* Type or paste password here:

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">