12

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?

Community
  • 1
  • 1
nacho4d
  • 43,720
  • 45
  • 157
  • 240

2 Answers2

3

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).

Matt Parlane
  • 453
  • 2
  • 11
3

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.

GOTO 0
  • 42,323
  • 22
  • 125
  • 158