How do I create a GUID / UUID?

How do I create a GUID / UUID?

To create a Globally Unique Identifier (GUID) or Universally Unique Identifier (UUID), you can use one of the following methods:

Use a library: There are several libraries available that can generate GUIDs/UUIDs for you. For example, you can use the uuid library in Node.js:

const uuid = require('uuid');

let guid = uuid.v4();
console.log(guid); // e.g., '3cce1e52-d906-4d7b-9b61-7d894f9f4b4c'

Use the crypto module: If you're using Node.js, you can use the crypto module to generate a random GUID/UUID:

const crypto = require('crypto');

function generateGUID() {
  return crypto.randomBytes(16).toString('hex');
}

let guid = generateGUID();
console.log(guid); // e.g., '932f2d27b2a44b8f8b07981c3a4776c3'

Use a Regular Expression: You can also use a regular expression to generate a GUID/UUID:

function generateGUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

let guid = generateGUID();
console.log(guid); // e.g., '3cce1e52-d906-4d7b-9b61-7d894f9f4b4c'

  • Date: