Generate GUID using JavaScript

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 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.   
  10. var guid = createGuid();  
Example 2:
  1. // http://guid.us/GUID/JavaScript  
  2.   
  3. function createGuid(){  
  4.    function S4() {  
  5.       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);  
  6.    }  
  7.    return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0,3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();  
  8. }  
  9.   
  10. var guid = createGuid();   
Example 3: 
  1. // http://note19.com/2007/05/27/javascript-guid-generator/  
  2.   
  3. function createGuid() {  
  4.    function s4() {  
  5.       return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);  
  6.    }  
  7.    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();  
  8. }  
  9.   
  10. 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.   
  3. function createGuid()  
  4. {  
  5.    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {  
  6.       var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);  
  7.       return v.toString(16);  
  8.    });  
  9. }  
  10.   
  11. var guid = createGuid();  
Ebook Download
View all
Learn
View all