Skip to content
JavaScript

UUID Generation

Generate a unique identifier compliant with UUID v4.

By EZ4Code Team
uuidunique-id

Code

function uuid() {
  if (crypto.randomUUID) return crypto.randomUUID();
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

Explanation

Prefers native crypto.randomUUID, with a fallback using Math.random.

More JavaScript Snippets