JavaScript Generate Random String

In the land of JavaScript, there are many ways in Javascript generate random strings that it doesn’t really matter which method is faster.

How Javascript generate random strings?

This javascript code will generate a random string of characters for your use in passwords, credit card numbers, or other sensitive information.

The function below takes an integer and returns a long string that is at least 10 characters long with each character being randomly selected from the alphabet. The number you input corresponds to the length of the generated string:

function getRandomString(length){  

var randChar = "";  

while (randChar.length < length) 

{

 randChar += Math.floor(Math.random() * 26); } 

return randChar; 

}

The Math.random():

The Math.random() function is a built-in javascript function. It returns a number with a uniform distribution, between 0 and 1.

var len = 10; 
var randChar = ""; 
while (len--)
{ randChar += Math.floor(Math.random() * 26); }

You can also use javascript in your browser to generate a random string:

The javascript code for generating a random string is very simple, it’s just the Math.random() function with no parameters and you can use this in your javascript to generate a random string of any length.

Also Read: Javascript isnteger Method

Follow us on Facebook

Leave a Comment