188

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

Community
  • 1
  • 1
Maggie
  • 5,661
  • 8
  • 40
  • 55
  • Is the only requirement to turn `1` into `0001` or is the requirement to padd all strings to have 4 digits, using zeros as placeholders? That's what it sounds like you're asking. – jcolebrand Mar 20 '11 at 04:55
  • I want to convert all the strings to have 4 digits using '0'as placeholders. – Maggie Mar 20 '11 at 04:58
  • 5
    Best, slickest answer on http://stackoverflow.com/questions/13859538/simplest-inline-method-to-left-pad-a-string `("0000" + n).slice(-4)` – gordon Feb 28 '17 at 17:52
  • or if your string could be longer than 4 digits: `(pad + mystr).slice(-Math.max(pad.length, mystr.length))` (same page, comment by Bruno) – gordon Feb 28 '17 at 17:59
  • 3
    There's a [padStart](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart) in the JavaScript spec now. If `x` contains the integer `1`, you can write `\`${x}\`.padStart(4, '0')` (if you want, can just write `x.padStart(4, '0')` if `x` is already a string rather than an integer). – ShreevatsaR Aug 26 '19 at 13:47

4 Answers4

411

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

Nimantha
  • 5,793
  • 5
  • 23
  • 56
96

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);
}
KooiInc
  • 112,400
  • 31
  • 139
  • 174
14
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.

kennebec
  • 98,993
  • 30
  • 103
  • 125
2

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"
Marcello Nuccio
  • 3,891
  • 1
  • 26
  • 28