190

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,923
  • 8
  • 41
  • 56
  • 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

415

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
  • 6,405
  • 6
  • 28
  • 69
  • 11
    Or just `var ans = pad.substring(str.length) + str` – Alcalyn Mar 03 '15 at 14:35
  • 81
    Or `var ans = ('0000'+str).substring(str.length);`. – Mogsdad Jun 03 '15 at 21:42
  • 4
    Or just `var ans = Array(4-str.length).join('0')+str` – David Mar 17 '16 at 09:09
  • Mogsdad nope... if you do something like str=12; ('0000'+str).substring(str.length); You will get "000012" the idea is to get "0012" – Martin Cisneros Capistrán Apr 19 '16 at 07:37
  • 1
    @MartinCisnerosCapistrán - Actually, Mogsdad's code snippet is right. In your code snippet (`str = 12;`), `str` is an integer, so `str.length` is undefined, which is treated as `0` in `substring(str.length)`, resulting in the full string being returned. Mogsdad's code snippet assumes that `str` is a string, as in `str = "12"` or `str = ""+12`. – Dan Nissenbaum Apr 28 '16 at 03:50
  • 10
    Or `(pad + str).slice(-pad.length)` :) – Marcelo Lazaroni Nov 29 '16 at 17:47
  • 1
    If your str might be longer than the needed padding here's a mashup of this string solution + borrowed idea from Bruno on http://stackoverflow.com/questions/13859538/simplest-inline-method-to-left-pad-a-string: `('0000'+str).substring(Math.min((""+str).length,4))` – gordon Feb 28 '17 at 18:19
  • Use ```("0000" + str).slice(-4)``` – TuinBoy Jan 03 '21 at 19:38
  • @David Maybe `Array(4-str.length+1).join('0')+str`. Array needs `n+1` elements to generate a `n` chars string. – TNT Feb 02 '21 at 17:52
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
  • 119,216
  • 31
  • 141
  • 177
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
  • 102,654
  • 32
  • 106
  • 127
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,901
  • 2
  • 28
  • 28