Generate a random password using JavaScript
Today we’ll show you how to generate a random password using JavaScript. Here, we’ll show you the most popular two methods to generate a random strong password using JavaScript.
Ways to generate a random password
1. Generate a password from given string
In this approach, we will create a custom function to get a random password where we have to pass the length of the password as a parameter. We’ll consider the string, number and symbol to generate a random password.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | function generatePassword(len) { var length = len ? len : 10; var string = "abcdefghijklmnopqrstuvwxyz"; // to upper var numeric = "0123456789"; var punctuation = "!@#$_"; var password = ""; var character = ""; while (password.length < length) { entity1 = Math.ceil(string.length * Math.random() * Math.random()); entity2 = Math.ceil(numeric.length * Math.random() * Math.random()); entity3 = Math.ceil(punctuation.length * Math.random() * Math.random()); hold = string.charAt(entity1); hold = password.length % 2 == 0 ? hold.toUpperCase() : hold; character += hold; character += numeric.charAt(entity2); character += punctuation.charAt(entity3); password = character; } password = password .split("") .sort(function() { return 0.5 - Math.random(); }) .join(""); return password.substr(0, len); } generatePassword(8); // Output: C6d#F@33 generatePassword(12); // Output: o4h@#1#4D@3D |
2. Use Math.random() method
In the next approach, we’ll use the Math.random()
method to cast a random number (in the range 0..1) to a base36 string (lowercase a-z plus 0-9) and remove the leading zero and decimal point using slice()
method. Here, we have used the toUpperCase()
method to get the uppercase char in the password.
1 2 3 4 5 6 7 8 9 | function generatePassword() { return ( Math.random().toString(36).slice(2) + Math.random().toString(36).toUpperCase().slice(2) ); } generatePassword(); // Output: ggpq0gv9iviVI1YEF4BGZ generatePassword(); // Output: bmsv4p3v4m1CFSR0V4CXH |
That’s it for today.
Thank you for reading. Happy Coding..!!