It is a common requirement to pad our display values to a specified size. This may involve padding to the left, right, or even center values. This is especially useful when generating fixed-width output. In this recipe, we will see how to pad our values by creating a useful, multipurpose padding function.
We will be using the basic tools provided by Node.
We want to create a function that will accept a string value, which will pad it to a specified size (number of characters) with a padding character. It should be able to pad our values to the left or right.
Padding can also provide some alignment functionality. For example, if we pad a value to the right, it will be left aligned, while padding to the left will right align our value.
Let's look at how we can accomplish this.