How to generate a random ID in JavaScript without a library

itwasmattgregg

Matt Gregg

Posted on April 22, 2021

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
💖 💪 🙅 🚩
itwasmattgregg
Matt Gregg

Posted on April 22, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related