DEV Community

loading...

How to generate a random ID in JavaScript without a library

itwasmattgregg profile image Matt Gregg Originally published at codegregg.com ・1 min read

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

Discussion (0)

pic
Editor guide