How to pad a string in JavaScript

Sometimes you need your string to be a set length, like maybe you have numbers that all need to be 10 characters long regardless of the number value. Or maybe you have a credit card number and want to just show the last 4 digits while everything else is replaced with an asterisk (*). Regardless of the reason, JavaScript now has built in methods to add the padded characters to either the start or the end of your string. Let’s begin with the padding at the start to get the idea going.

Say you have an invoice system that needs it’s invoice numbers to be 10 characters, but you are only up to invoice number 4532. You’ll want to have six zeros prepended to the invoice number for display. To do this, we will use JavaScript’s padStart() method. This method takes two parameters: targetLength & padString. targetLength is how long the string will be once the desired number of characters have been added. padString is the character that will be used for padding; if none is supplied, JavaScript will use " " (U+0020 'SPACE').

Using the invoice example above, your code would look like this:

let invoiceNumber = "4532"
invoiceNumber.padStart(10, '0')
// Output: "0000004532"

The padEnd() method works the same way but appends the padding character to the end of the string. So, our example would look like this instead:

let invoiceNumber = "4532"
invoiceNumber.padEnd(10, '0')
// Output: "4532000000"

More Information: