How do I create a GUID / UUID?
How do I create GUIDs (globally unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.
How do I create a GUID / UUID?
How do I create GUIDs (globally unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.
With my years of experience working on JavaScript projects, I’ve found that UUIDs (Universally Unique Identifiers), or GUIDs (Globally Unique Identifiers), as defined in RFC 4122, are incredibly useful for ensuring uniqueness. You can create RFC-compliant UUIDs with a few lines of JavaScript code, but there are a few things you should keep in mind:
Math.random()
.For production environments, I strongly recommend using a robust and well-maintained implementation such as the uuid
module.
Building on Miro’s advice, here’s a JavaScript function that I’ve used in various projects to create a UUID based on RFC 4122, section 4.4:
function createUUID() {
var s = [];
var hexDigits = '0123456789abcdef';
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = '-';
var uuid = s.join('');
return uuid;
}
This function generates a random UUID string in the format ‘xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx’, where each ‘x’ is a hexadecimal digit and ‘y’ is a hexadecimal digit from 8, 9, a, or b."
Taking it a step further from the previous example, I often use a quicker method for generating GUID-like strings in the format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX. While this approach doesn’t produce a standard-compliant GUID per RFC 4122, it’s quite efficient for generating unique identifiers in a browser environment.
Here’s a method I’ve frequently utilized:
/**
* Generates a GUID-like string.
* @returns {string} The generated GUID-like string.
*/
function guid() {
function _p8(s) {
var p = (Math.random().toString(16) + '000000000').substr(2, 8);
return s ? '-' + p.substr(0, 4) + '-' + p.substr(4, 4) : p;
}
return _p8() + _p8(true) + _p8(true) + _p8();
}
This function provides a fast way to generate unique identifiers in a browser environment. However, for applications requiring standard-compliant GUIDs, it’s still best to use a well-maintained implementation like the uuid
module.