transformation
String.prototype.padStart
Returns a new string padded on the left with padString (default ' ') until it reaches targetLength. Added in ES2017; the original is returned unchanged if it is already long enough.
str.padStart(targetLength[, padString]) Parameters
| Parameter | Purpose |
|---|---|
| targetLength | Desired final length in UTF-16 code units |
| padString | String used for padding (default ' '); truncated if too long |
Examples
console.log('5'.padStart(3, '0')); Prints '005'
console.log('42'.padStart(6)); Prints ' 42'
console.log('abc'.padStart(2, '0')); Prints 'abc' (already >= targetLength)
console.log('x'.padStart(5, 'ab')); Prints 'ababx'
Gotcha
Counts UTF-16 code units, so emoji (surrogate pairs) count as 2. If padString is empty the result is unchanged.
Related methods
String.prototype.padEnd
Returns a new string padded on the right with padString (default ' ') until it reaches targetLength. Added in ES2017.
String.prototype.repeat
Returns a new string containing count copies of the original string concatenated together. Added in ES2015; count must be a non-negative finite integer.
String.prototype.trimStart
Returns a new string with leading whitespace removed. Added in ES2019 (aliased as trimLeft for legacy code).
String.prototype.replace
Returns a new string with the first match of pattern replaced. Pattern can be a string (only the first occurrence) or a RegExp (all occurrences when the g flag is set).
String.prototype.replaceAll
Returns a new string with every occurrence of pattern replaced. Added in ES2021; if pattern is a RegExp it must have the g flag or replaceAll throws TypeError.