1 pad
String.prototype.PadLeft = function(totalWidth, paddingChar)
{
if ( paddingChar != null )
{
return this.PadHelper(totalWidth, paddingChar, false);
} else {
return this.PadHelper(totalWidth, ' ', false);
}
}
String.prototype.PadRight = function(totalWidth, paddingChar)
{
if ( paddingChar != null )
{
return this.PadHelper(totalWidth, paddingChar, true);
} else {
return this.PadHelper(totalWidth, ' ', true);
}
}
String.prototype.PadHelper = function(totalWidth, paddingChar, isRightPadded)
{
if ( this.length < totalWidth)
{
var paddingString = new String();
for (i = 1; i <= (totalWidth - this.length); i++)
{
paddingString += paddingChar;
}
if ( isRightPadded )
{
return (this + paddingString);
} else {
return (paddingString + this);
}
} else {
return this;
}
}
2 uuid
function uuid() { 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); }); }
function uuid4() { function hex (s, b) { return s + (b >>> 4 ).toString (16) + // high nibble (b & 0b1111).toString (16); // low nibble } let r = crypto.getRandomValues (new Uint8Array (16)); r[6] = r[6] >>> 4 | 0b01000000; // Set type 4: 0100 r[8] = r[8] >>> 3 | 0b10000000; // Set variant: 100 return r.slice ( 0, 4).reduce (hex, '' ) + r.slice ( 4, 6).reduce (hex, '-') + r.slice ( 6, 8).reduce (hex, '-') + r.slice ( 8, 10).reduce (hex, '-') + r.slice (10, 16).reduce (hex, '-'); }
function generateUUID() { // Public Domain/MIT
var d = new Date().getTime();//Timestamp
var d2 = (performance && performance.now && (performance.now()*1000)) || 0;//Time in microseconds since page-load or 0 if unsupported
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16;//random number between 0 and 16
if(d > 0){//Use timestamp until depleted
r = (d + r)%16 | 0;
d = Math.floor(d/16);
} else {//Use microseconds since page-load if supported
r = (d2 + r)%16 | 0;
d2 = Math.floor(d2/16);
}
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
参考:
https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript?page=1&tab=votes#tab-top