Generate GUID in JavaScript

Generating a GUID using JavaScript in Internet Explorer (Windows OS) is as simple as using the Scriptlet.TypeLib ActiveX object.

<head>
<title>Generate GUID using JavaScript by DevCurry.com</title>
<script type="text/javascript">
    function GenerateGUID() {
        return (new ActiveXObject("Scriptlet.TypeLib")
                                    .GUID.substr(1, 36));
    }
    alert(GenerateGUID());
</script>
</head>


The substring removes the curly braces {} from the generated id. However the script shown above is pretty much useless as it is IE/Windows specific. I was looking out for a script to generate GUID in JavaScript that works Cross browser. Here’s a script by John Stockton that generates a random string of type GUID using JavaScript.

Note: As pointed by Dunni in the comments section, the string generated may not necessarily be unique. Also make sure you read this Is GUID really unique?

<head>
<title>Generate GUID using JavaScript by DevCurry.com</title>
<script type="text/javascript">
function G() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}

var guid = (G() + G() + "-" + G() + "-" + G() + "-" + 
G() + "-" + G() + G() + G()).toUpperCase();

alert(guid);
</script>
</head>

OUTPUT

Generate GUID in JavaScript

3 comments:

  1. This is OK as it does generate a GUID-style string but remember that the whole point of a GUID is that it is Globally unique, this method does not guarantee this so use with caution!

    ReplyDelete
  2. Yes that's a good point. I forgot to mention that in the post. Thanks for your comment.

    ReplyDelete