Random alphanumeric strings in JS
Sometimes in larger JS apps, I'll need a way to generate unique IDs for a large number of objects.
The following is a nice one-liner for that purpose:
Math.random().toString(36).slice(2)
To add a bit more entropy, you can use:
+new Date() + Math.random().toString(36).slice(2)
Written by Kevin Ennis
Related protips
2 Responses
Perhaps you meant:
(Math.random()+ +new Date).toString(36).replace('.','')
over 1 year ago
·
Nope, I meant what I posted.
The reason for including the date first is to reduce the (admittedly very low) likelihood of collisions between the random strings.
By prefixing the date, you reduce the risk of duplication -- because the colliding hashes would have to have been generated within a millisecond of eachother to actually cause a problem.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#