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 needed const chrs ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; //function that returns string function generateString(length) { //initialize emtpy string let result = ' '; //get given characters length const charactersLength = chrs.length; //loop that gives random character for each iteration for ( let i = 0; i < length; i++ ) { result += chrs.charAt(Math.floor(Math.random() * charactersLength)); } //return the generated string return result; } //call function and print the returned string console.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.
RELATED TAGS
CONTRIBUTOR
View all Courses