String.prototype.padStart()
The zero-padding method. Its two rules worth remembering: it never truncates, and a multi-character pad is cut off mid-way rather than overshooting.
Demo
Zero-padding a number is what this method is for, and the first case is the whole idiom. The second case is the rule that surprises people: a string already longer than the target is returned UNCHANGED — padStart never truncates, so it cannot be used to enforce a maximum width. The multi-character pad repeats and is then cut to fit exactly, which is why 'ab' padding to length 5 gives 'ababx' rather than overshooting. An empty pad string is a silent no-op.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| targetLength | number | yes | Desired final length. A value at or below the current length means no padding at all — the string comes back untouched. |
| padString | string | no (' ') | Text to pad with, repeated as needed and TRUNCATED to fit exactly. An empty pad string does nothing at all. |
Return value
string — A new string of at least targetLength, padded on the LEFT. If the string is already that long it is returned unchanged — never truncated.
Common patterns
const hhmm = `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
const id = String(n).padStart(6, '0'); // '000042'
const fixed = s.slice(0, 8).padStart(8);
Examples
Pitfalls
'abcdef'.padStart(3, '0')
'abcdef'.slice(0, 3).padStart(3, '0')
(5).padStart(3, "0")
String(5).padStart(3, '0')
'x'.padStart(4, '\u{1F600}')
'x'.padStart(4, '-')
el.textContent = ' x'
text-align: right
When to use
- Zero-padding numbers for times, dates and identifiers
- Fixed-width output in a monospaced context — logs, terminals
- Making numeric strings sort correctly as text
- Right-aligning short values in plain text
- You need a maximum width too → slice first, then pad
- Padding on the right → padEnd
- Aligning in HTML → CSS, not spaces
- Formatting numbers for humans → toLocaleString or Intl.NumberFormat
Notes
FAQ
Because padding and truncating are different operations, and conflating them would make the method lossy. If you need an exact width, slice first and then pad — the two together are explicit about discarding data.
s.slice(0, n).padStart(n, '0');