DEV Community

Cover image for Fastest Way to Generate Random Strings in JavaScript

Fastest Way to Generate Random Strings in JavaScript

Oyetoke Toby on February 10, 2020

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...
Collapse
 
wwaterman12 profile image
wwaterman12

Nice function! But one thing I noticed is that this will only work for random alpha-numeric strings up to a certain length. If you want to have something longer, you should call the method recursively. Something like:

const generateRandomString = function (length, randomString="") {
  randomString += Math.random().toString(20).substr(2, length);
  if (randomString.length > length) return randomString.slice(0, length);
  return generateRandomString(length, randomString);
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rohaq profile image
rohaq

Yep, looks like it tops out at 12-13 characters for me, demo here: jsfiddle.net/mberwk8a/2/

Collapse
 
pcbailey profile image
Phillip Rhodes

Hi, thanks for the simple, straight-forward article! I just wanted to point out a small error in your one-liner. You define the length variable, but you still used a hard-coded "6" instead of it in the expression.

Collapse
 
maulerjan profile image
Jan Mauler

Don't use the .substr(2, ...) at the end, because you risk having empty string as a result. The result of Math.random() can be 0, so if you substr(2, ...), you will end up with an empty string.

Collapse
 
diek profile image
diek

Do you like base20 for something special?

Collapse
 
oyetoket profile image
Oyetoke Toby

No reason actually, I just like using it.

Collapse
 
austindd profile image
Austin

Just to clarify for people who don't know, the radix argument for toString goes from 2 to 36, and you need to use 36 to include all alphanumeric characters in the alphabet. Using 20 will omit more than half of the alphabetic letters from the output.