Generate random characters and numbers in JavaScript?


At first, set the characters and numbers −

var storedCharacters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

To generate randomly, use Math.random(). Following is the code −

Example

function generateRandom3Characters(size) {
   var generatedOutput= '';
   var storedCharacters =
   '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
   var totalCharacterSize = storedCharacters.length;
   for ( var index = 0; index < size; index++ ) {
      generatedOutput+=storedCharacters.charAt(Math.floor(Math.random() *
      totalCharacterSize));
   }
   return generatedOutput;
}
console.log(generateRandom3Characters(3));

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo136.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo136.js
lq4

Updated on: 11-Sep-2020

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements