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
:-)
(8.357963780872523e+31).toString(36)
-> 221fr2y11ebk4cog84wok
which is exactly I want.6.936gwtrpf69(e+20)
.How can I get the same string 221fr2y11ebk4cog84wok
from 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?
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With