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('.','')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.
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside