Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random string/characters in JavaScript

I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9].

What's the best way to do this with JavaScript?

like image 278
Tom Lehman Avatar asked Aug 28 '09 21:08

Tom Lehman


People also ask

How do you randomize a string in JavaScript?

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.

How do you randomly return a string?

The quickest way is to use the Math. random() method. The above code will generate a random string of 8 characters that will contain numbers only. To generate an alpha-numeric string, you can pass an integer value between 2 and 36 to the toString() method called radix .


2 Answers

I think this will work for you:

function makeid(length) {
    var result           = '';
    var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * 
 charactersLength));
   }
   return result;
}

console.log(makeid(5));
like image 151
csharptest.net Avatar answered Oct 07 '22 19:10

csharptest.net


//Can change 7 to 2 for longer results.
let r = (Math.random() + 1).toString(36).substring(7);
console.log("random", r);

Note: The above algorithm has the following weaknesses:

  • It will generate anywhere between 0 and 6 characters due to the fact that trailing zeros get removed when stringifying floating points.
  • It depends deeply on the algorithm used to stringify floating point numbers, which is horrifically complex. (See the paper "How to Print Floating-Point Numbers Accurately".)
  • Math.random() may produce predictable ("random-looking" but not really random) output depending on the implementation. The resulting string is not suitable when you need to guarantee uniqueness or unpredictability.
  • Even if it produced 6 uniformly random, unpredictable characters, you can expect to see a duplicate after generating only about 50,000 strings, due to the birthday paradox. (sqrt(36^6) = 46656)
like image 2977
doubletap Avatar answered Oct 07 '22 21:10

doubletap