If we'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 which means 40 characters of hex.
Method 2
If we have to do this client-side, perhaps try the uuid module
Method 3
If we have to do this client-side and we don't have to support old browsers, we can do it without dependencies
Solution 5:
A small probability producing short strings or even an empty string (if the random number is 0), which may break your application. Here is a solution:
Second, both the original and the solution above limit the string size N to 16 characters. The following will return a string of size N for any N (but note that using N > 16 will not increase the randomness or decrease the probability of collisions):
Explanation:
Pick a Random number in the range [0,1], i.e. between 0 (inclusive) and 1 (exclusive).
Convert the number to a base-36 string, i.e. using characters 0-9 and a-z.
Pad with zeros (solves the first issue).
Slice off the leading zeros, i.e. prefix and extra padding zeros.
Repeat the string enough times to have at least N number of characters in it (by Joining empty strings with the shortest random string used as the delimiter).