DEV Community

Discussion on: Fastest Way to Generate Random Strings in JavaScript

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
Richard Hodgson

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