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?
Something like this should work
Call with default charset [a-zA-Z0-9] or send in your own:
The most compact solution, because
slice
is shorter thansubstring
. Subtracting from the end of the string allows to avoid floating point symbol generated byrandom
function:or even
The simplest way is:
This generate random strings of 5 characters based on the current time. Example output is
4mtxj
or4mv90
or4mwp1
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:
This will generate a random string of 4 or 5 characters, always diferent. Example output is like
30jzm
or1r591
or4su1a
In both ways the first part generate a random number. The
.toString(36)
part cast the number to a base36 (alphadecimal) representation of it.If you are using Lodash or Underscore, then it so simple:
How about something like this:
Date.now().toString(36)
Not very random, but short and quite unique every time you call it.