lotsoftools

UUID V4 Generator

This snippet page provides a succinct and efficient UUID V4 generator in JavaScript.

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);
  });
}
uuidv4();

This JavaScript function generates a UUID following the UUID V4 format. The UUID is returned as a string ready for use.

The character placeholders 'x' and 'y' in the format are replaced with hexadecimal digits generated randomly or following a specific rule. This is done using the replace function and a callback that generates the digits.

The random digits for 'x' are created using the Math.random function and bit manipulation. For 'y', a specific bit is set to ensure compliance with the UUID V4 format.