Random alpha-numeric string in JavaScript?

Pavel picture Pavel · May 23, 2012 · Viewed 253.9k times · Source

What's the shortest way (within reason) to generate a random alpha-numeric (uppercase, lowercase, and numbers) string in JavaScript to use as a probably-unique identifier?

Answer

JAR.JAR.beans picture JAR.JAR.beans · Sep 19, 2012

I just came across this as a really nice and elegant solution:

Math.random().toString(36).slice(2)

Notes on this implementation:

  • This will produce a string anywhere between zero and 12 characters long, usually 11 characters, due to the fact that floating point stringification removes trailing zeros.
  • It won't generate capital letters, only lower-case and numbers.
  • Because the randomness comes from Math.random(), the output may be predictable and therefore not necessarily unique.
  • Even assuming an ideal implementation, the output has at most 52 bits of entropy, which means you can expect a duplicate after around 70M strings generated.