June 10, 2011

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

Giving me +1 tells me you liked this article! Thanks in advance


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Generate GUID in JavaScript"
  1. Dunni said...
    June 10, 2011 at 6:10 AM

    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!

  2. Suprotim Agarwal said...
    June 10, 2011 at 6:28 AM

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

 

Copyright © 2009-2013 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions