# convert ‘1’ to ‘0001’ in JavaScript [duplicate]

## 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]);

### Solution 1:

This is a clever little trick (that I think I’ve seen on SO before):

``````var str = "" + 1
``````

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 ðŸ˜‰

Happy coding.

### Solution 2:

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:
return Array(n-String(this).length+1).join(str||'0')+this;
}
//examples
``````

If you want to use this for negative numbers also:

Related:  Using JQuery hover with HTML image map
``````Number.prototype.padLeft = function (n,str) {
return (this < 0 ? '-' : '') +
Array(n-String(Math.abs(this)).length+1)
.join(str||'0') +
(Math.abs(this));
}
``````

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);
}
``````

### Solution 3:

``````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.

### Solution 4:

I use the following object:

``````function Padder(len, pad) {
if (len === undefined) {
len = 1;
} else if (pad === undefined) {
}

}

var s = what.toString();
``````var zero4 = new Padder(4);