How to create a GUID in Javascript
Two years ago, I needed to generate GUID for an ExtJS project (purpose was to create on-the-fly a unique id for tchat messages user was sending). Hereafter the function I used (source should by StackOverFlow and other forums, I dont’ remember exactly), still working.
generateGUID : function() { return ((typeof(window.crypto) != 'undefined' && typeof(window.crypto.getRandomValues) != 'undefined') ? function() { // If we have a cryptographically secure PRNG var buf = new Uint16Array(8); window.crypto.getRandomValues(buf); var S4 = function(num) { var ret = num.toString(16); while(ret.length < 4){ ret = "0"+ret; } return ret; }; return (S4(buf[0])+S4(buf[1])+"-" +S4(buf[2])+"-"+S4(buf[3])+"-" +S4(buf[4])+"-"+S4(buf[5])+S4(buf[6])+S4(buf[7])); } : function() { // Otherwise, just use Math.random 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); } ); // replace } )(); }// generateGUID
You must be logged in to post a comment.