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

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

3 comments:

Dunni said...

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!

Suprotim Agarwal said...

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

Unknown said...

Very nice code!