An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
September 15, 2021 05:27 pm GMT
Original Link: https://dev.to/antoomartini/making-random-and-unique-id-with-javascript-4c8c
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:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To