Introduction

I had a requirement to generate the GUID type id using JavaScript. I started worked on that, in the mean while I came across some sites and they already have given some snippets to generate the GUID.
Here, I will give those compilations of those snippets.
Generate random unique id / GUID using Math.Random
Example 1:
  1. // http://slavik.meltser.info/the-efficient-way-to-create-guid-uuid-in-javascript-with-explanation/
  2. function CreateGuid() {
  3. function _p8(s) {
  4. var p = (Math.random().toString(16)+"000000000").substr(2,8);
  5. return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
  6. }
  7. return _p8() + _p8(true) + _p8(true) + _p8();
  8. }
  9. var guid = createGuid();
Example 2:
  1. // http://guid.us/GUID/JavaScript
  2. function createGuid(){
  3. function S4() {
  4. return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
  5. }
  6. return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0,3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();
  7. }
  8. var guid = createGuid();
Example 3:
  1. // http://note19.com/2007/05/27/javascript-guid-generator/
  2. function createGuid() {
  3. function s4() {
  4. return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  5. }
  6. return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
  7. }
  8. var guid = createguid();
Generate GUID using the Regular Expression
Example 4:
  1. //http://byronsalau.com/blog/how-to-create-a-guid-uuid-in-javascript/
  2. function createGuid()
  3. {
  4. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
  5. var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
  6. return v.toString(16);
  7. });
  8. }
  9. var guid = createGuid();