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:
-
- function CreateGuid() {
- function _p8(s) {
- var p = (Math.random().toString(16)+"000000000").substr(2,8);
- return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
- }
- return _p8() + _p8(true) + _p8(true) + _p8();
- }
-
- var guid = createGuid();
Example 2:
-
-
- function createGuid(){
- function S4() {
- return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
- }
- return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0,3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();
- }
-
- var guid = createGuid();
Example 3:
-
-
- function createGuid() {
- function s4() {
- return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
- }
- return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
- }
-
- var guid = createguid();
Generate GUID using the Regular Expression
Example 4:
-
-
- 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);
- });
- }
-
- var guid = createGuid();