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?
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?
Math.random is bad for this kind of thing
Option 1
If you're able to do this server-side, just use the crypto module
The resulting string will be twice as long as the random bytes you generate; each byte encoded to hex is 2 characters. 20 bytes will be 40 characters of hex.
Option 2
If you have to do this client-side, perhaps try the uuid module
Option 3
If you have to do this client-side and you don't have to support old browsers, you can do it without dependencies
A newer version with es6 spread operator:
[...Array(30)].map(() => Math.random().toString(36)[3]).join('')
30
is arbitrary number, you can pick any token length you want36
is the maximum radix number you can pass to numeric.toString(), which means all numbers and a-z lowercase letters3
is used to pick the 3rd number from the random string which looks like this:"0.mfbiohx64i"
, we could take any index after0.
This is as clean as it will get. It is fast too, http://jsperf.com/ay-random-string.
This works for sure
Here is a test script for the #1 answer (thank you @csharptest.net)
the script runs
makeid()
1 million
times and as you can see 5 isnt a very unique. running it with a char length of 10 is quite reliable. I've ran it about 50 times and haven't seen a duplicate yet:-)
note: node stack size limit exceeds around 4 million so you cant run this 5 million times it wont ever finish.
Fast and improved algorithm. Does not guarantee uniform (see comments).