The String padStart() method
By Flavio Copes
Learn how the JavaScript padStart() method adds characters to the start of a string until it reaches a target length, using a space or a pad string you provide.
padStart() adds characters to the beginning of a string until the string reaches a length you specify. It was introduced in ES2017.
It takes the target length, and optionally the string to pad with:
padStart(targetLength [, padString])
If you omit the pad string, it pads with spaces:
'5'.padStart(3) //' 5'
Like all string methods, it returns a new string. The original is not changed.
When is padding useful?
The typical case is fixed-width formatting. Say you’re building a clock and hours and minutes are numbers. You want 9:05, not 9:5:
const hours = '9'
const minutes = '5'
hours.padStart(2, '0') //'09'
minutes.padStart(2, '0') //'05'
Same idea for invoice or order numbers that need a fixed number of digits:
'42'.padStart(6, '0') //'000042'
It’s also handy for right-aligning values in plain text output, like a terminal report, by padding with spaces.
What happens with unusual inputs?
If the string is already at the target length, or longer, nothing happens. You get the string back unchanged:
'invoice'.padStart(4) //'invoice'
If the pad string is too long to fit, it gets truncated:
'42'.padStart(6, '2026') //'202642'
'42'.padStart(5, '2026') //'20242'
In the second example only 202 fits, so the rest of the pad string is dropped.
If you pass a pad string that’s empty, no padding is added at all.
Why doesn’t it work on numbers?
Here’s the pitfall. Padding is most useful with numbers, but padStart() is a string method. Calling it on a number throws:
const price = 42
price.padStart(6, '0') //TypeError: price.padStart is not a function
The fix is to convert the number to a string first:
String(price).padStart(6, '0') //'000042'
One more detail: the length is counted in UTF-16 code units, the same units .length uses. Most characters count as one, but emoji count as two, so padded emoji strings can look shorter than you expect.
To pad the other side of the string, see padEnd(). It works exactly the same way, but appends the padding instead.
Related posts about js: