Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 15, 2021 05:27 pm GMT

Making random and unique ID with Javascript

Last week, I needed to find a way to generate a unique id to get names for phone files on ios systems. Anyway, googling around, I found this simple function.

All you have to do is call it, where you need to generate the id, and pass the desired length of the id.
And magic! It returns an id made with characters and numbers (in this example, of course!)

const makeRandomId= (length) => {      let result = ''      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'      for (let i = 0; i < length; i++ ) {        result += characters.charAt(Math.floor(Math.random() * characters.length));     }     return result;  }

charAt: The charAt() method returns the character at a specified index in a string.
floor(): The floor() method rounds a number DOWNWARDS to the nearest integer, and returns the result.
random(): Math.random() returns a random number between 0 (inclusive), and characters.length (exclusive):

Math.random() used with Math.floor() can be used to return random integers.

That's all! :)


Original Link: https://dev.to/antoomartini/making-random-and-unique-id-with-javascript-4c8c

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To