Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross browser random string (Math.random()*1e32).toString(36)

Tags:

javascript

I use (Math.random()*1e32).toString(36) as a simple random string generator. It is very simple and works well and fullfils my needs (a temporal random to be used for ids, etc)

In chrome, safari, firefox and ie Math.random()*1e32 generates numbers like: 8.357963780872523e+31 :-)

  • In chrome, safari and firefox such number is converted into a string (8.357963780872523e+31).toString(36) -> 221fr2y11ebk4cog84wok which is exactly I want.
  • However in ie11 the string result is 6.936gwtrpf69(e+20).

How can I get the same string 221fr2y11ebk4cog84wokfrom 8.357963780872523e+31 in a cross browser manner?

BTW: I got the idea of this random string from this thread: Random alpha-numeric string in JavaScript?

like image 807
nacho4d Avatar asked Sep 17 '15 08:09

nacho4d


People also ask

How to randomize 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 create a random number in JavaScript?

Generating Javascript Random Numbers Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.


2 Answers

Keeping in mind that Math.random() returns a value between 0 and 1 (exclusive), and that numbers in JavaScript have 53 bits mantissa as per IEEE-754, a safe way to get a random integer would be

Math.random() * Math.pow(2, 54)

So a random alphanumeric string could be obtained from

(Math.random() * Math.pow(2, 54)).toString(36)

Note that there is no guarantee about the number of characters, which could be anything between 1 and 11 depending on the order of magnitude of the random value.

like image 68
GOTO 0 Avatar answered Oct 26 '22 03:10

GOTO 0


As fas as I can see, you don't need to multiply the random number by such a large number. Try this:

Math.random().toString(36).slice(2)

Does that suffice? It's a slightly shorter string but it's consistent in all browsers (that I tested).

like image 3
Matt Parlane Avatar answered Oct 26 '22 05:10

Matt Parlane