How to use .charAt() method In Javascript
- Make a string consisting of Alphabets (lowercase and uppercase), Numbers, and Special Characters.
- We will use Math.random() and Math.floor() methods to generate a number between 0 and l-1 (where l is the length of the string).
- To get the character of the string of a particular index we can use .charAt() method.
- This will keep concatenating the random character from the string until the password of the desired length is obtained.
Example: This example implements the above approach.
/* Function to generate combination of password */
function generatePass() {
let pass = '';
let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz0123456789@#$';
for (let i = 1; i <= 8; i++) {
let char = Math.floor(Math.random()
* str.length + 1);
pass += str.charAt(char)
}
return pass;
}
console.log(generatePass());
Output
UJmkWOZc
How to Generate a Random Password using JavaScript ?
This article will show you how to generate a random password that may consist of alphabets, numbers, and special characters. This can be achieved in various ways.
These are the following ways:
Table of Content
- Using .charAt() method
- Using .toString() method
- Using a Custom Function with Character Codes