JavaScript Generate UUID/GUID for RFC 4122 Version 4 Compliant with Regular Expression

What is UUID/GUID

A Universally Unique IDentifier (UUID) – also called a Global Unique IDentifier (GUID) – is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen (‘-‘ U+002D). A typical UUID is baef6775-eb3a-4ac9-85d3-70e4aa0d9d94.

A version 4 UUID is defined in RFC 4122: 128 randomly-generated bits with six bits at certain positions set to particular values. For example,

The digit at position 1 above is always4‘ and the digit at position 2 is always one of ‘8‘, ‘9‘, ‘A‘ or ‘B‘. It doesn’t matter whether the letters A-F are upper or lower case.

Procedure

The procedure to generate a version 4 UUID is as follows:

  1. Generate 16 random bytes (=128 bits)
  2. Adjust certain bits according to RFC 4122 section 4.4 as follows:
    1. set the four most significant bits of the 7th byte to 0100’B, so the high nibble is ‘4’
    2. set the two most significant bits of the 9th byte to 10’B, so the high nibble will be one of ‘8’, ‘9’, ‘A’, or ‘B’.
  3. Convert the adjusted bytes to 32 hexadecimal digits
  4. Add four hyphen ‘-‘ characters to obtain blocks of 8, 4, 4, 4 and 12 hex digits
  5. Output the resulting 36-character string “XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX”

Solutions

Below are one-liner(ish) solutions for an RFC 4122 version 4 compliant solution.

Modern Browsers:

Node.js:

Other Environments (old broswers etc less IE 11):

E.g:

Side Note

  • Be aware that UUID uniqueness relies heavily on the underlying random number generator (RNG). The solution above uses Math.random() for brevity, however Math.random() is not guaranteed to be a high-quality RNG. See Adam Hyland’s excellent writeup on Math.random() for details. For a more robust solution, consider something like node-uuid.js

  • This gist describes how to determine how many IDs can be generated before reaching a certain probability of collision. For example, with 3.26×1015 version 4 RFC4122 UUIDs you have a 1-in-a-million chance of collision.

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA