How to generate a Unique ID in JavaScript
In this article, we will show you how to generate a unique ID in JavaScript. There are several ways to generate a unique identifier using JavaScript.
Checkout more articles on JavaScript
Method 1:
1 2 3 4 5 6 7 8 9 | function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } console.log(uuidv4()); // Output: b9eac503-fe73-49a7-a19c-e469aa255c92 |
Method 2:
1 2 3 4 5 6 7 8 9 | function uuid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } console.log(uuid()); // Output: 852e9a4f-616d-45a4-8fe4-9dc37afcf482 |
Method 3:
1 2 3 4 5 6 | const uid = function(){ return Date.now().toString(36) + Math.random().toString(36).substr(2); } console.log(uid()); // Output: kyg0z26npc43wq7vaa |
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂