String.prototype.padStart
Pads a string on the left to a given length.
Available since: ES2017
Syntax
str.padStart(targetLength, padString)Parameters
| Parameter | Type | Description |
|---|---|---|
| targetLength | number | The length to pad the string to. |
| padString | string | Optional. What to pad with; a space by default. |
Return value
stringA new string of the required length.
Examples
A leading zero for hours and minutes:
console.log(String(5).padStart(2, '0'));
console.log(String(12).padStart(2, '0'));Output:
05
12The companion padEnd() pads on the right:
console.log('1'.padEnd(4, '0'));Output:
1000Notes
If the string is already at least the target length, it is returned unchanged. The method exists only on strings, so convert a number with String() first.
See also
- String.prototype.repeat — Repeats a string a given number of times.
- Number.prototype.toFixed — Formats a number with a given number of decimal places.
- String.prototype.padEnd — Pads a string on the right to the desired length.
Related recipes
In the tutorial
- String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.