How to: Create a GUID / UUID in Javascript - Byron Salau

Posted by | May 05, 2013 | javascript | 15 Comments

Today i needed to create a guid or (Globally Unique Identifier) in my JavaScript application. I saw some pretty bad solutions out there until i saw one that was using regex. I thought that was a brilliant idea so I made some changes and compressed it down to the following utility method.

This will create an rfc4122 version 4 compliant guid

function createGuid()
{
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}

Usage:
var uuid = createGuid();
>>> "e2ece964-0315-4b91-b411-20f9868ce7d4"

  • http://www.frisb.com ashley brener

    Byron

    Thank you for this extremely useful code snippet.
    I ran some benchmarking that may interest you, your algorithm is 2.5 times faster without regex (on google chrome):

    http://jsperf.com/guid-vs-random-string

    Ashley.

    • byrons

      Thanks Ashley, yeah i mate of mine recently brought to my attention the performance increase you can get by not using regular expression. I think i will have to do a revisit to this post. One of the things that really appeals to me about the regex approach though is the small amount of code. So hopefully we can come up with a non-regex solution that is still pretty elegant.

  • Charlie Magee

    Thanks. Worked perfect.

  • dingdong

    Where is the link to the original solution?

  • Jason Padvorac

    Thank you! Clean and simple. :)

  • Valdaros
  • http://www.vuongtran.net/ Vuong Tran

    Thanks man, that is helpful.

  • Kapil Deshmukh

    Awesome … You save my time

  • Cindy Teller

    yeah but it’s slow when creating hundreds per minute, use this one instead (just view source and copy their javascript): http://infonibble.com/tools/guid-generator

    • Paul Kleimeyer

      That’s OK if you don’t need a version 4 UUID.

  • Seb

    what’s the logic/idea behind (r&0×3|0×8)?

    • n00dl3

      from wikipedia:
      >Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, a, or b (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479).

      this code:
      ((Math.random()*16|0)&0×3|0×8).toString(16)
      will generate “9″ or “8″ or “a” or “b”