convert '1' to '0001' in JavaScript [duplicate]
Possible Duplicate:
Is there a JavaScript function that can pad a string to get to a determined length?
How can I convert convert '1' to '0001' in JavaScript without using any 3rd party libraries. I have done this in php using spritf: $time = sprintf('%04.0f',$time_arr[$i]);
This is a clever little trick (that I think I've seen on SO before):
var str = "" + 1
var pad = "0000"
var ans = pad.substring(0, pad.length - str.length) + str
JavaScript is more forgiving than some languages if the second argument to substring is negative so it will "overflow correctly" (or incorrectly depending on how it's viewed):
That is, with the above:
- 1 -> "0001"
- 12345 -> "12345"
Supporting negative numbers is left as an exercise ;-)
Just to demonstrate the flexibility of javascript: you can use a oneliner for this
function padLeft(nr, n, str){
return Array(n-String(nr).length+1).join(str||'0')+nr;
}
//or as a Number prototype method:
Number.prototype.padLeft = function (n,str){
return Array(n-String(this).length+1).join(str||'0')+this;
}
//examples
console.log(padLeft(23,5)); //=> '00023'
console.log((23).padLeft(5)); //=> '00023'
console.log((23).padLeft(5,' ')); //=> ' 23'
console.log(padLeft(23,5,'>>')); //=> '>>>>>>23'
If you want to use this for negative numbers also:
Number.prototype.padLeft = function (n,str) {
return (this < 0 ? '-' : '') +
Array(n-String(Math.abs(this)).length+1)
.join(str||'0') +
(Math.abs(this));
}
console.log((-23).padLeft(5)); //=> '-00023'
Alternative if you don't want to use Array
:
number.prototype.padLeft = function (len,chr) {
var self = Math.abs(this)+'';
return (this<0 && '-' || '')+
(String(Math.pow( 10, (len || 2)-self.length))
.slice(1).replace(/0/g,chr||'0') + self);
}
String.prototype.padZero= function(len, c){
var s= this, c= c || '0';
while(s.length< len) s= c+ s;
return s;
}
dispite the name, you can left-pad with any character, including a space. I never had a use for right side padding, but that would be easy enough.
I use the following object:
function Padder(len, pad) {
if (len === undefined) {
len = 1;
} else if (pad === undefined) {
pad = '0';
}
var pads = '';
while (pads.length < len) {
pads += pad;
}
this.pad = function (what) {
var s = what.toString();
return pads.substring(0, pads.length - s.length) + s;
};
}
With it you can easily define different "paddings":
var zero4 = new Padder(4);
zero4.pad(12); // "0012"
zero4.pad(12345); // "12345"
zero4.pad("xx"); // "00xx"
var x3 = new Padder(3, "x");
x3.pad(12); // "x12"
精彩评论