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
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; }
Here is an example of calling the function:
pwdLen = 10; window.alert("A random string of " + pwdLen + "characters: " + generatePassword(pwdLen));
Try it
Generate a random password of 8 characters.
If you enjoyed this post, make sure you subscribe to my RSS feed!