DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Matt Gregg
Matt Gregg

Posted on • Originally published at codegregg.com

How to generate a random ID in JavaScript without a library

I'm sure this is posted in a ton of places already but I thought I would share a method I sometimes use to generate random strings of (numbers + letters) with javascript. This function returns the first 6 characters of a randomly generated string. Passing 36 to the toString method tells it to return numbers 0-9 and every letter in the alphabet, you can adjust the 6 in the substr method if you want a longer or shorter ID.

const id = function() {
  return Math.random()
    .toString(36)
    .substr(2, 6);
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

πŸŒ–πŸŒ—πŸŒ˜ Turn on dark mode in Settings