Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tạo GUID / UUID trong JavaScript

Cách 1: Math.random() (không khuyên dùng production)

function createUUID() {
  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);
  });
}

Cảnh báo: Math.random() không cryptographically secure — có thể trùng lặp.

Cách 2: npm uuid package (RFC4122 compliant)

$ npm install uuid
const uuid = require('uuid');
console.log(uuid.v4()); // random UUID v4
console.log(uuid.v1()); // time-based UUID v1

Cách 3: Native crypto.randomUUID() (Modern browsers, Node 14.17+)

console.log(crypto.randomUUID()); // "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbb84bed"
// Hoặc Node: require('crypto').randomUUID()

Khuyến nghị: Dùng crypto.randomUUID() (native) hoặc uuid package. Tránh Math.random() cho production.