🤯 50% Off! 700+ courses, assessments, and books

A Utility Function for Padding Strings and Numbers

James Edwards
Share

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.