In this shot, we will learn to generate a string composed of randomly chosen characters using JavaScript.
We can achieve this using the Math.random()
function, which gives a random number between 0
and 1
. Let's take a look at an example.
//declare the characters you neededconst chrs ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';//function that returns stringfunction generateString(length) {//initialize emtpy stringlet result = ' ';//get given characters lengthconst charactersLength = chrs.length;//loop that gives random character for each iterationfor ( let i = 0; i < length; i++ ) {result += chrs.charAt(Math.floor(Math.random() * charactersLength));}//return the generated stringreturn result;}//call function and print the returned stringconsole.log(generateString(20));
In the above code snippet:
chrs
that need to be in the generated string.for
loop in line 14.chrs
.for
loop that iterates until it reaches the string's given length.for
loop using the Math.random()
function.generateString()
and pass the length of the string as a parameter and print the returned string.