A Utility Function for Padding Strings and Numbers

Share this article

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.

Frequently Asked Questions (FAQs) about JavaScript Utility Function for Padding Strings and Numbers

What is a utility function in JavaScript?

In JavaScript, a utility function is a reusable piece of code that can be used across multiple scripts or applications. These functions are designed to perform a specific task or a set of tasks, and they can be called upon whenever needed. They help in reducing the redundancy of code, making the code more readable and maintainable. The utility function for padding strings and numbers, for example, is used to add extra characters to the beginning or end of a string or number until it reaches a specified length.

How does the padStart() method work in JavaScript?

The padStart() method in JavaScript is used to pad the start of a string with another string until the resulting string reaches a certain length. The padding is applied from the start (left) of the current string. It takes two arguments: the target length of the string and the string to pad with. If the target length is less than the length of the original string, the method returns the original string without any padding.

Can I use the padStart() method with numbers?

Yes, you can use the padStart() method with numbers in JavaScript. However, since padStart() is a method of the String prototype, you need to convert the number to a string first. Once the number is converted to a string, you can use the padStart() method to add leading zeros or any other characters.

What is the difference between padStart() and padEnd() methods in JavaScript?

The main difference between padStart() and padEnd() methods in JavaScript lies in where the padding is applied. The padStart() method adds padding to the beginning (left) of the string, while the padEnd() method adds padding to the end (right) of the string. Both methods take two arguments: the target length and the string to pad with.

How can I create a custom padding function in JavaScript?

Creating a custom padding function in JavaScript involves defining a function that takes a string or number, the target length, and the padding character as arguments. The function then uses a loop or the built-in padStart() or padEnd() methods to add the padding character to the string or number until it reaches the target length.

What are some common use cases for padding strings or numbers in JavaScript?

Padding strings or numbers in JavaScript is commonly used in formatting output for display. For example, you might want to display numbers with a fixed number of digits, with leading zeros if necessary. Padding can also be used to align text in columns by adding spaces, or to create strings of a certain length for testing purposes.

Can I use padding functions with non-string and non-number data types?

The padding functions in JavaScript, including the built-in padStart() and padEnd() methods, are methods of the String prototype. This means they can only be directly used with strings. However, you can convert other data types to strings using the toString() method or the String constructor, and then apply the padding functions.

Are there any limitations or caveats when using the padStart() and padEnd() methods?

The padStart() and padEnd() methods in JavaScript are relatively new additions to the language, introduced in ECMAScript 2017. This means they may not be supported in older browsers or environments. If you need to support older environments, you might need to use a polyfill or create a custom padding function.

How can I pad a string or number with trailing zeros in JavaScript?

To pad a string or number with trailing zeros in JavaScript, you can use the padEnd() method. This method works similarly to the padStart() method, but adds the padding to the end of the string. If you’re working with a number, remember to convert it to a string first.

Can I use multiple characters for padding in JavaScript?

Yes, you can use multiple characters for padding in JavaScript. When using the padStart() or padEnd() methods, the padding string is repeated as many times as necessary to reach the target length. If the padded string exceeds the target length, it is cut off to fit.

James EdwardsJames Edwards
View Author

James is a freelance web developer based in the UK, specialising in JavaScript application development and building accessible websites. With more than a decade's professional experience, he is a published author, a frequent blogger and speaker, and an outspoken advocate of standards-based development.

stringsutilities
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week