I was missing a simple and elegant method for padding a number with leading zeroes in javascript.
A typical example of leading zeroes is when you want to show the current time and you want the time to be formatted like hh:mm. There is no problem when it’s 12:40, but when is five minutes past one, you get 1:5, which is not what you would expect. You want it formatted like 01:05. The same happens with dates and in several other situations.
Yesterday I found the best solution I’ve seen for this problem. Before that, let’s see possible solutions.
Usually, needing only one zero, I would do something like:
h = (h < 10) ? ("0" + h) : h;
This is not bad at all, but is not elegant. The problem is, what if we want it to be formatted with 3 digits? Then, using the same schema, we can end up with something like:
h = (h < 100) ? ( (h >= 10) ? ("0" + h) : ("00" + h) ) : h;
Man, this is ugly and unreadable!! Maybe it will improve with an if/else, but it will be bad anyway. Probably if you need to do something like that, you will create a function that will handle this problem and then, you will call that function saying you want h padded with 3 zeros. But there is another solution that does not require you to use or create such a funciton…
Have a look for two digit and three digit:
("0" + h).slice (-2); // devolverá "01" si h=1; "12" si h=12
("00" + h).slice (-3); // "001" si h=1; "012" si h=12;"123" si h = 123
I don’t know what are you thinking after seeing this solution, but I got flashed when I saw it. Just amazing!
Let’s explain what’s going on. The code above only concatenates the “00″ with the number we want to format (e.g: “00″ + 12 = “0012″) and then, we get the last three digits using the slice string function (that’s why you have a -3). Guess what? The last three characters are “012″ which is the string we want.
Of course this solution is not only limited to leading zeroes, you can use it with leading spaces, or whatever character you want.
Sources:
- Padding zero in Javascript
- Little tricks: string padding in Javascript of Eneko Alonso blog (originally seen here)

Español