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?
The simplest way is:
(new Date%9e6).toString(36)
This generate random strings of 5 characters based on the current time. Example output is 4mtxj
or 4mv90
or 4mwp1
The problem with this is that if you call it two times on the same second, it will generate the same string.
The safer way is:
(0|Math.random()*9e6).toString(36)
This will generate a random string of 4 or 5 characters, always diferent. Example output is like 30jzm
or 1r591
or 4su1a
In both ways the first part generate a random number. The .toString(36)
part cast the number to a base36 (alphadecimal) representation of it.