How to generate UUID’s/GUID’s with Javascript?

Asked

Viewed 837 times

2

I need to create UUID’s/GUID’s with Javascript, but I did not find any function in the documentation. Know/recommend an existing library, which manages valid and satisfactorily random UUID’s?

2 answers

3


Versions based on crypto.getRandomValues() can ensure a lower crash rate than Math.random().

function uuid() {

    // Retorna um número randômico entre 0 e 15.
    function randomDigit() {
    
        // Se o browser tiver suporte às bibliotecas de criptografia, utilize-as;
        if (crypto && crypto.getRandomValues) {
        
            // Cria um array contendo 1 byte:
            var rands = new Uint8Array(1);
            
            // Popula o array com valores randômicos
            crypto.getRandomValues(rands);
            
            // Retorna o módulo 16 do único valor presente (%16) em formato hexadecimal
            return (rands[0] % 16).toString(16);
        } else {
        // Caso não, utilize random(), que pode ocasionar em colisões (mesmos valores
        // gerados mais frequentemente):
            return ((Math.random() * 16) | 0).toString(16);
        }
    }
    
    // A função pode utilizar a biblioteca de criptografia padrão, ou
    // msCrypto se utilizando um browser da Microsoft anterior à integração.
    var crypto = window.crypto || window.msCrypto;
    
    // para cada caracter [x] na string abaixo um valor hexadecimal é gerado via
    // replace:
    return 'xxxxxxxx-xxxx-4xxx-8xxx-xxxxxxxxxxxx'.replace(/x/g, randomDigit);
}

console.log(uuid());

You may notice that the return string has 2 fixed values, 4 for the 3rd block and 8 for the 4th. This is part of the specification for Random Guids version 4.

Source.

  • Can you explain how the algorithm works?

  • How the crypto.getRandomValues? It is compatible with multiple browsers?

  • @jbueno Explanation in comments, thanks for the suggestion.

  • @Arturotemplario Most modern browsers support the library crypto.

  • Great +1 @Onosendai

  • @Onosendai I think better than this just by making an AJAX call and generating server side kkkk thank you very much, I think it serves perfectly for my purposes

Show 1 more comment

1

I did some research and found some functions that might help you.

To generate UUID you can use the function below:

function create_UUID(){
    var dt = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (dt + Math.random()*16)%16 | 0;
        dt = Math.floor(dt/16);
        return (c=='x' ? r :(r&0x3|0x8)).toString(16);
    });
    return uuid;
}
console.log(create_UUID());

To generate the GUID can be done as below:

function S4() {
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1); 
}

function create_GUID(){
    return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0,3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();
}

console.log(create_GUID());

References:

http://www.w3resource.com/javascript-exercises/javascript-math-exercise-23.php http://guid.us/GUID/JavaScript

  • And how it works?

  • The functions create_UID() and create_GUID() return a string. So just call the function as I did in console.log(create_UUID()) it will already generate random code.

  • I want to know how the algorithm that creates UUID works.

  • In the links I passed the references have more details about the algorithm.

  • But I don’t speak English.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.