To generate random string/ characters in JavaScript, use Math.random(). We are generating 6 random characters here from the following characters −
'ABCDEFGHIJKLMNOabcdefghijklmnopqrstuvwxyzPQRSTUVWXYZ';
Example
Following is the code −
function generateRandomNumber(numberOfCharacters) { var randomValues = ''; var stringValues = 'ABCDEFGHIJKLMNOabcdefghijklmnopqrstuvwxyzPQRSTUVWXYZ'; var sizeOfCharacter = stringValues.length; for (var i = 0; i < numberOfCharacters; i++) { randomValues = randomValues+stringValues.charAt(Math.floor(Math.random() * sizeOfCharacter)); } return randomValues; } console.log(generateRandomNumber(6));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo270.js.
Output
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo270.js qIcoCT