The Tech Platform

Feb 1, 20221 min

How to Generate Random String in JavaScript?

Sometimes, programmers require to create a string which is generated by selecting the random characters. Random String Generator helps to create a random string by choosing some characters randomly. This string can be a simple character string or an alpha-numeric string.

Syntax:

Math.random()

In this example, the Math.random() method is used to generate random characters from the specified characters (A-Z, a-z, 0-9).

The for loop is used to loop through the number passed into the generateString() function. During each iteration, a random character is generated.

Code:

const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
 

 
function generateString(length) {
 
let result = ' ';
 
const charactersLength = characters.length;
 
for ( let i = 0; i < length; i++ ) {
 
result += characters.charAt(Math.floor(Math.random() * charactersLength));
 
}
 

 
return result;
 
}
 
console.log("Program to Generate Random String in JavaScript ","\n");
 
console.log("Random String will be :",generateString(5));

Output:

The Tech Platform

www.thetechplatform.com

    0