Create a random ID with JavaScript (of custom length!)

We can start by creating a random ID – and worry about it being unique later.

// short random string for ids – not guaranteed to be unique

const randomId = function(length = 6) {

 return Math.random().toString(36).substring(2, length+2);

};

The function works by creating a random number (Math.random()), which gives us a decimal number between 0 and 1.

Then we convert the number to a string with a radix of 36 toString(36). This radix represents digits beyond 0-9 with letters, so the random number is converted to a random string.

Finally, we cut off the 0. at the start of the decimal number, and end the string at our length argument .substring(2, length+2) – (+2 for the 2 characters we lost at the start of string!).

Now we can call the randomId function and get an ID that’s 6 characters, but you can also pass a length (up to 10*) if you want a shorter or longer ID.

If you want to go up to lengths of 20 you could do return (Math.random().toString(36).substring(2) + Math.random().toString(36).substring(2)).substring(0, length);.

Now you should get a random ID each time you call randomId, to the length of your choice – but it’s not guaranteed to be unique.

Leave a comment

Your email address will not be published. Required fields are marked *