JavaScript GUID Generator

Mar
19

I recently found an interesting forum post which detailed how to generate GUIDs using JavaScript on the fly.  Its very simple and looks as follows:

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

function generateGuid(){
        return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()).toUpperCase();
}

 

Originally posted by  Dr John Stockton on thescripts.com.

3 Responses to “JavaScript GUID Generator”

  1. The term 0×10000 in function s4() seems to be the source of error in my use of the proposed javascript GUID creator. Here is my proposed solution:

    Untitled Document

    function S4() {
    // replace 0×10000 with this format: *parseInt(’10000′,16); RDF
    return ((1+Math.random())*parseInt(’10000′,16)).toString(16).substring(1);
    }
    function generateGuid(){
    return (S4()+S4()+”-”+S4()+”-”+S4()+”-”+S4()+”-”+S4()+S4()+S4()).toUpperCase();
    }

    // test the GUID generator
    alert(generateGuid());

  2. Oops, I have two more fixes to make the GUID a little more usable and a little more random…

    Untitled Document

    function S4() {
    // add a seed to randome number generator, RDF
    now = new Date();
    seed = now.getSeconds();
    // replace 0×10000 with this format: *parseInt(’10000′,16); RDF
    // replace substring(1) with a 4 digit hex string like this: substring(1,5); RDF
    return ((1+Math.random(seed))*parseInt(’10000′,16)).toString(16).substring(1,5);
    }
    function generateGuid(){
    return (S4()+S4()+”-”+S4()+”-”+S4()+”-”+S4()+”-”+S4()+S4()+S4()).toUpperCase();
    }

    // test the GUID generator
    document.writeln(generateGuid());

  3. I made a few more fixes…

    Untitled Document

    function S4() {
    // add a seed to randome number generator, RDF
    now = new Date();
    seed = now.getSeconds();
    // replace 0×10000 with this format: *parseInt(’10000′,16); RDF
    // replace substring(1) with a 4 digit hex string like this: substring(1,5); RDF
    return ((1+Math.random(seed))*parseInt(’10000′,16)).toString(16).substring(1,5);
    }
    function generateGuid(){
    return (S4()+S4()+”-”+S4()+”-”+S4()+”-”+S4()+”-”+S4()+S4()+S4()).toUpperCase();
    }

    // test the GUID generator
    document.writeln(generateGuid());

Leave a Reply