String. prototype. padStart()
Pads a string on the left with the given text until it reaches the specified length. Perfect for leading zeros.
- Returns
- A new string at least
targetLengthlong, padded on the left. - Changes the original
- No
Example
#const minutes = 5
const seconds = 9
const time = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
console.log(time)
console.log('42'.padStart(6, '0'))Definition and usage
#The padStart() method adds characters to the start of a string until it reaches the desired length. By default it pads with spaces, but you can supply your own text, such as "0". If the string is already long enough, it comes back unchanged.
It is most often used to format numbers: minutes and seconds (05:09), order numbers with leading zeros, or right-aligning columns of text. Convert the number to a string first, for example with String(n), since padStart() is a string method.
When the padding text is longer than needed, it gets trimmed down. The original does not change; the method returns a new string.
Syntax
#string.padStart(targetLength)
string.padStart(targetLength, padString)Parameters
#targetLength
number
The target length of the result. If it is less than or equal to the string's length, the string comes back unchanged.padString
string, optional
The text used for padding, repeated and trimmed as needed. Defaults to a space.
More examples
#const scores = [
['Mia', 1200],
['Jack', 85],
['Eva', 430]
]
for (const [name, points] of scores) {
console.log(name.padEnd(6) + String(points).padStart(5))
}console.log('4815'.padStart(12, '*'))
console.log('7'.padStart(4, 'ab'))
console.log('Long text'.padStart(3))Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#padStart()works on strings. For a number, writeString(n).padStart(2, "0"), because calling it directly on a number throws aTypeError.- For formatting dates and times according to locale conventions, also consider
Intl.DateTimeFormat, which adds leading zeros on its own.
Related entries
#- String.prototype.padEnd()Pads a string on the right with the given text until it reaches the specified length.
- String.prototype.repeat()Returns a new string made up of the given number of copies of the original.
- String.prototype.lengthThe length of a string, i.e. the number of UTF-16 code units. The property is read-only.
- Number.prototype.toFixed()Converts a number into a string with a given number of decimal places.
- Template literalsText templates in backticks: insert values with ${} and span multiple lines.
Spotted a mistake or missing an example? Write to us.