How to Generate Random Strings in JavaScript

There are so many ways to generate random strings in JavaScript and it doesn't really matter which method is faster.

The method I like using most is Math.random()

I made a video on it:

Basically the idea is to use Math.random(), then you can convert it to string and do some simple string manipulation on it.

To get random numbers, I would use something like below:

Math.ceil(Math.random()*10000)

To get random strings with numbers only, I would use:

Math.random().toString().substr(2, 5)

Fortunate .toString() has a param called radix that you can pass in numbers between 2 - 36 which will cast the generated numbers to the radix characters that fall between the given number. The radix is also known as base and its for representing numeric values

To get a random number between 0-1:

Math.random().toString(2).substr(2, 5)

To get a random number between 0-5:

Math.random().toString(5).substr(2, 5)

Starting from 11/12, it will start introducing letters. So to get a fully random string:

Math.random().toString(20).substr(2, 6)

With this you can now write your awesome random string generator:

const generateRandomString = function(){
return Math.random().toString(20).substr(2, 6)
}

To be able to change the length of the output:

const generateRandomString = function(length=6){
return Math.random().toString(20).substr(2, length)
}

One liner

const generateRandomString = (length=6)=>Math.random().toString(20).substr(2, 6)

That's all.

If you know of any other faster ways, please I would love to see it in the comment section.

Thanks

No Comments Yet