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?
P粉3121957002023-10-13 12:38:49
I just discovered this is a very nice and elegant solution:
1 |
|
Comments for this implementation:
Math.random()
, the output may be predictable and therefore not necessarily unique. P粉9856865572023-10-13 09:56:40
If you only want to allow specific characters, you can also do this:
1 2 3 4 5 6 |
|
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Fiddle: http://jsfiddle.net/wSQBx/2/
Alternatively, to use the base36 method described below, you can do the following:
1 2 3 |
|