How to generate a random alphanumeric string in JavaScript?
P粉7757887232023-10-12 23:03:12
0
2
740
What is the shortest way (within reason) to generate a random alphanumeric (uppercase, lowercase and numeric) string to use as a possible unique identifier in JavaScript?
I just discovered this is a very nice and elegant solution:
Math.random().toString(36).slice(2)
Comments for this implementation:
This will produce a string between 0 and 12 characters in length, typically 11 characters since floating point stringification removes trailing zeros.
It will not generate uppercase letters, only lowercase letters and numbers.
Since the randomness comes from Math.random(), the output may be predictable and therefore not necessarily unique.
Even assuming an ideal implementation, the output will have at most 52 bits of entropy, which means you may end up with duplicates after generating ~70M strings.
If you only want to allow specific characters, you can also do this:
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
I just discovered this is a very nice and elegant solution:
Comments for this implementation:
Math.random()
, the output may be predictable and therefore not necessarily unique.If you only want to allow specific characters, you can also do this:
Here is a jsfiddle to demonstrate: http://jsfiddle.net/wSQBx/
Another approach is to use a special string to tell the function what type of characters to use. You can do this:
Fiddle: http://jsfiddle.net/wSQBx/2/
Alternatively, to use the base36 method described below, you can do the following: