Skip to content

Instantly share code, notes, and snippets.

@cyjake
Created January 16, 2012 14:49
Show Gist options
  • Save cyjake/1621200 to your computer and use it in GitHub Desktop.
Save cyjake/1621200 to your computer and use it in GitHub Desktop.
UID Generating in JavaScript
// 还需要了解的:
// - 什么是 UID
// - 这四种方式优劣
function getId() {
return "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".replace(/x/g, function() {
return Math.floor(Math.random()*16).toString(16).toUpperCase();
});
}
function generateGuid() {
var result, i, j;
result = '';
for(j=0; j<32; j++) {
if( j == 8 || j == 12|| j == 16|| j == 20)
result = result + '-';
i = Math.floor(Math.random()*16).toString(16).toUpperCase();
result = result + i;
}
return result;
}
// http://stackoverflow.com/questions/3242324/javascript-dateobj-gettime-for-a-uid-is-the-length-not-fixed
Math.random().toString(36).substr(2,9)
// http://stackoverflow.com/questions/6248666/how-to-generate-short-uid-like-ax4j9z-in-js
function generateUIDNotMoreThan1million() {
return ("0000" + (Math.random()*Math.pow(36,4) << 0).toString(36)).substr(-4)
}
@mio991
Copy link

mio991 commented Oct 4, 2014

If you replace the String "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" with "xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx" it should be standard conform.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment