A Utility Function for Padding Strings and Numbers

Welcome to the first post in what will be an ongoing series of articles which looks at a single JavaScript function — something small but powerful, that does one thing well. To kick the series off, this article focuses on a function for padding values with leading characters. This type of function is particularly useful for formatting integer dates and times.

What The Function Does

The pad function starts with a string or number, and pads the input with leading characters up to a specified string length. While the function can pad any value with any other value, perhaps the most common use is to pad a number with leading zeros — for example, to normalize the hours, minutes and seconds in a 24-hour clock. The code for the pad function is shown below.

function pad(input, length, padding)
{
  while((input = input.toString()).length + (padding = padding.toString()).length < length)
  {
    padding += padding;
  }
  return padding.substr(0, length - input.length) + input;
}

As you can see from the code, the function takes three arguments. The first argument, input, is the value you want to be padded. The second argument, length, is the desired length of the padded string. The third argument, padding, is the padding value, often just a single character.

Using the Function

To give an example of usage, the Date.getHours() function returns a number representing the hour in the specified date according to local time. To normalize the hour to a two-digit numeric string, you would pass it through pad like this:

var hours = pad(new Date().getHours(), 2, 0);

Taking the previous example a step further, you could create a complete 24-hour time string, like this:

var date = new Date(), time = [
  pad(date.getHours(), 2, 0),
  pad(date.getMinutes(), 2, 0),
  pad(date.getSeconds(), 2, 0)
];
alert( time.join(':') );

Keys to the Function

First and foremost, we have to convert both the input and padding values to strings, so that the result of the operation is always concatenation, and not numerical addition even if both the values are numbers. We could just insist that the inputs must be strings, but that would make the function far less convenient to use. For example, you wouldn’t be able to pass it the output of Date.getHours(), without converting to a string yourself. The most obvious way to write a function like this would be to simply add the padding string to the start of the input string until the desired length is reached, as shown below.

while(input.length < length)
{
  input = padding + input;
}
return input;

The problem with that approach is that it will only work correctly if the padding string is a single character, or if the output length minus the input length is perfectly divisible by the padding length. For example, if we passed an input value of "7", an output length of 6, and the padding string "0x", the result would be "0x0x0x7". This is clearly longer than the specified output length.

To get around that problem, we precompile the padding first — concatenating as many instances of it as we need to reach or exceed the output length. Then we add a precise substring of that to the input string, in order to create the exact output length as specified:

while(input.length + padding.length < length)
{
  padding += padding;
}
return padding.substr(0, length - input.length) + input;

Using the same example as before, the result of this improved code would be "0x0x07", because only one character of the final padding instance is actually used.

Conclusion

And there you have it, a short and sweet function that performs a simple, but incredibly useful task. We have created a function that helps with formatting dates, times, currency, and rgb-hex values. Be sure to check back in the coming weeks for more short and sweet functions.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Jagwinder Singh

    Useful function. Thanks

  • pb

    hi. im excited about this site. javascript is my weakness as a front end developer. can you give an example how you would use this? Like the html that you would use the function on?

    thanks for any info.

    • http://www.brothercake.com/ James Edwards

      You would use it with values that need padding characters for normalization, the most common example of which is to pad numeric strings, so that they have a predictable number of digits. The date and time examples I have in this article use numbers which might be less than 10, and pad them all to 2 digits, so a figure that started as “5″ would end up as “05″.

  • chuck jungmann

    I’d like to suggest another solution for zero-padding numbers that I use in javascript as well as xpath (where I came up with this idea):

    function padnum(val, len)
    {
    return String(Math.pow(10,len)+val).substring(1);
    }

    It’s not as flexible as your function, and it obviously would need some bounds-checking, but for numbers about which you know the range of possibilities, it’s enough.

    Even simpler, for well-known values like zero-padding a part of a date or time that we know is less than 100, use:
    return String(100+val).substring(1);

  • http://www.brothercake.com/ James Edwards

    Nice :-)

    Perhaps some slight modifications to padnum:

    return (Math.pow(10, (len || 2)) + val).toString().substr(1);

    Using (len || 2) so the length can default to 2 if undefined (or zero); casting with toString because it’s faster; and use “substr” rather than “substring” because it takes fewer characters! (and is interchangeable in this case)