How to generate a string of randomly chosen characters in JS
Overview
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.
Code
//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));
Explanation
In the above code snippet:
- Line 2: We declare and initialize the string of characters
chrsthat need to be in the generated string. - Line 5: We define a function that takes the length of the string as a parameter and returns the generated string with the given length.
- Line 8: We declare and initialize an empty string to store each character generated by the
forloop in line 14. - Line 11: We store the length of the characters that we gave in
chrs. - Line 14: We have a
forloop that iterates until it reaches the string's given length. - Line 15: We get each random character for each iteration of the
forloop using theMath.random()function. - Line 19: We return the generated string.
- Line 23: We make a function call on the function
generateString()and pass the length of the string as a parameter and print the returned string.