solvit.io

Generate a random UUID v4 value with JavaScript

Solution #1
function uuid()
{
    var seed = Date.now();
    if (window.performance && typeof window.performance.now === "function") {
        seed += performance.now();
    }

    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (seed + Math.random() * 16) % 16 | 0;
        seed = Math.floor(seed/16);

        return (c === 'x' ? r : r & (0x3|0x8)).toString(16);
    });

    return uuid;
}
Example
var value = uuid();
// the generated value is random, but it will follow this pattern:
// value = 'e7b71c50-2161-4669-ba52-a05200177659';
Solution #2

Use broofa/node-uuid project to generate better UUID v1 or v4 values.

Find more solutions about: , ,