How to generate a Unique ID in JavaScript
📅January 15, 2022
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
- scroll-to-a-specific-element-using-javascript" title="Scroll to a specific element using JavaScript">Scroll to a specific element using JavaScript
- How to insert an element after another element in JavaScript
- string-contains-a-valid-vimeo-url-using-javascript" title="Check if the string contains a valid Vimeo URL using JavaScript">Check if the string contains a valid Vimeo URL using JavaScript
- How to copy text to the clipboard using JavaScript
- number-in-javascript" title="Remove the leading zero from a number in JavaScript">Remove the leading zero from a number in JavaScript
Method 1:
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:
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:
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..!! 🙂