Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (13.1k points)

I want a string of 5 characters picked randomly from the set [a-zA-Z0-9]. What is the best way to do it?

1 Answer

0 votes
by (7k points)

You can do it like this:

function makeString(length) {

   var result  = '';

   var characters  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

   var charactersLength = characters.length;

   for ( var i = 0; i < length; i++ ) {

      result += characters.charAt(Math.floor(Math.random() * charactersLength));

   }

   return result;

}

console.log(makeString(5));

Want to be a full stack developer? Check out the full stack developer course from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...