String.prototype.padStart(): fixed-width text (ES2017)
What you’ll learn
Section titled “What you’ll learn”- What
padStart(targetLength, padString)returns and how the filler is repeated and cut. - How to build zero-padded IDs, clock times, right-aligned amounts and masked card numbers.
- The edge cases: strings that are already long, empty fillers, negative numbers and emoji.
- When a number formatter is a better choice than string padding.
Summary
Section titled “Summary”TL;DR: str.padStart(targetLength, padString = " ") returns a new string of at least targetLength UTF-16 code units, with padString repeated (and cut to fit) before the original text. If the string is already that long, it comes back unchanged. It was added in ECMAScript 2017 together with its mirror image, padEnd().
The problem it solves
Section titled “The problem it solves”Fixed-width text shows up everywhere: invoice numbers such as INV-000042, 09:05 clock times, right-aligned columns in a plain-text receipt. Before ES2017 every codebase carried its own loop, or a tiny dependency, to put characters in front of a string.
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. All outputs shown were produced with Node.js 22.23.
// Before ES2017: a hand-written helper (or a dependency) for every zero-padded ID.function leftPad(value, width, fill = ' ') { let text = String(value); while (text.length < width) text = fill + text; return text;}console.log(leftPad(42, 6, '0'));
// ES2017: built in.console.log(String(42).padStart(6, '0'));console.log('7'.padStart(3)); // default fill is a spaceconsole.log(`[${'7'.padStart(3)}]`);Output:
000042000042 7[ 7]The hand-written loop also has a subtle bug: with a multi-character fill it can overshoot the width. padStart always cuts the filler to the exact length.
How it works
Section titled “How it works”// Fragment: signaturestr.padStart(targetLength)str.padStart(targetLength, padString)The specification (StringPaddingBuiltinsImpl and StringPad) defines these steps:
- Convert
thisto a string, andtargetLengthto an integer withToLength(soNaNand negative values become0). - If
targetLengthis not greater than the string’slength, return the string unchanged. The filler is not even converted. - Use
" "whenpadStringisundefined; otherwise convert it withToString. If it is the empty string, return the original string. - Repeat the filler, cut it to
targetLength - lengthcode units, and put it in front.
console.log('abc'.padStart(10, '123')); // filler repeats, then is cut to fitconsole.log('abc'.padStart(6, '12345')); // filler cut to 3 code unitsconsole.log('abc'.padStart(2, '0')); // already long enough: unchanged, never truncatedconsole.log('abc'.padStart(6, '')); // empty filler: unchangedconsole.log('abc'.padStart(-1, '0')); // negative or NaN length counts as 0console.log('5'.padStart('3', 0)); // arguments are converted: '3' -> 3, 0 -> '0'console.log('😀'.length, '😀'.padStart(3, '*')); // length counts UTF-16 code unitsconsole.log(String(-5).padStart(3, '0')); // the sign is just another charactertry { 'x'.padStart(Infinity, '-');} catch (error) { console.log(error.constructor.name, '-', error.message);}console.log('x'.padStart(Infinity, '')); // empty filler returns before building anythingOutput:
1231231abc123abcabcabcabc0052 *😀0-5RangeError - Invalid string lengthxThe method is generic: it works on anything that converts to a string, but calling it on null or undefined throws a TypeError. A number has no padStart method, so convert it first with String(n) or a template literal. The RangeError message is V8’s wording; other engines word it differently.
Realistic example
Section titled “Realistic example”The OrdersPortal admin screens need sortable invoice numbers, clock times, a masked card reference and a right-aligned amount column:
// orders-format.mjs - display helpers for the OrdersPortal admin screens.
// INV-000123: fixed-width invoice numbers that also sort correctly as strings.export function invoiceNumber(sequence) { if (!Number.isSafeInteger(sequence) || sequence < 0) { throw new RangeError(`invalid invoice sequence: ${sequence}`); } return `INV-${String(sequence).padStart(6, '0')}`;}
// Show only the last four digits of a stored card reference.export function maskCard(last4, totalLength = 16) { return last4.slice(-4).padStart(totalLength, '•');}
// 09:05 from minutes since midnight.export function clockTime(minutes) { const h = Math.floor(minutes / 60); const m = minutes % 60; return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;}
// Zero-pad a signed integer without putting zeros in front of the minus sign.export function signedPad(n, width) { const digits = String(Math.abs(n)).padStart(width, '0'); return n < 0 ? `-${digits}` : digits;}
// Right-align amounts in a monospaced column.export function amountColumn(amounts, width = 10) { return amounts.map((a) => a.toFixed(2).padStart(width));}
const ids = [123, 9, 45210].map(invoiceNumber);console.log(ids);console.log([...ids].sort()); // string sort matches numeric orderconsole.log(maskCard('4242'));console.log(clockTime(545), clockTime(1439));console.log(signedPad(-7, 3), signedPad(7, 3));console.log(amountColumn([5, 129.5, 1024.99]).join('\n'));Output:
[ 'INV-000123', 'INV-000009', 'INV-045210' ][ 'INV-000009', 'INV-000123', 'INV-045210' ]••••••••••••424209:05 23:59-007 007 5.00 129.50 1024.99Zero padding is what makes the string sort match the numeric order, but only while every number fits the width. Invoice 1,000,000 becomes INV-1000000, which sorts before INV-045210. Choose a width with room to grow, or sort by the number.
For the padding side of the same receipt (labels, dot leaders, fixed-width records), see padEnd().
Common mistakes
Section titled “Common mistakes”- Expecting truncation.
'1234567'.padStart(6, '0')returns all seven characters. If the width is a hard limit,slicefirst and decide which end to keep. - Calling it on a number.
(42).padStart(6, '0')throwsTypeError: 42.padStart is not a function. UseString(42)first. - Padding negative numbers.
String(-5).padStart(3, '0')gives0-5. Pad the absolute value and add the sign back, or useIntl.NumberFormat. - Counting characters as
length. Width is measured in UTF-16 code units, so emoji and other astral characters count as two, and combining accents count separately. See Unicode Support. - Aligning in a proportional font. Spaces line up columns only in a monospaced font. In HTML, use CSS (
text-align: right,font-variant-numeric: tabular-nums) instead. - Formatting numbers by hand.
padStartknows nothing about decimals, grouping or locales.
When to use it and when not to
Section titled “When to use it and when not to”Use padStart for fixed-width text: IDs, codes, clock fields and monospaced columns. Prefer a number formatter when the value is a number that people read:
// Alternatives that format numbers instead of stringsconst n = 7;console.log(n.toLocaleString('en-US', { minimumIntegerDigits: 3, useGrouping: false }));console.log(new Intl.NumberFormat('en-US', { minimumIntegerDigits: 2 }).format(-5));Output:
007-05| Need | Use |
|---|---|
| Zero-padded ID or code | String(n).padStart(width, '0') |
| Padding at the end, labels, dot leaders | padEnd() |
| Signed or localized numbers | Intl.NumberFormat with minimumIntegerDigits |
| Dates and times for display | Intl.DateTimeFormat or toLocaleTimeString |
| A run of one character | repeat() |
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, padStart is supported in Chrome 57, Edge 15, Firefox 48, Safari 10 (including iOS), Node.js 8.0.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported it. TypeScript types it in lib.es2017.string.d.ts; add es2017 or later to lib only if a project pins an older one. For legacy browsers, core-js provides a polyfill.
Interview questions
Section titled “Interview questions”1. What does 'abc'.padStart(2, '0') return, and why?
'abc'. When the target length is not greater than the current length, the method returns the string unchanged. It never truncates.
2. How is a multi-character filler applied?
It is repeated and then cut to exactly the missing length, so 'abc'.padStart(6, '12345') is '123abc'. An empty filler returns the original string.
3. Why can padStart produce the wrong visual width?
It counts UTF-16 code units, not visible characters or terminal columns. An emoji counts as two units, a decomposed accent adds a unit, and East Asian wide characters take two columns while counting as one unit.
4. Senior scenario: OrdersPortal stores invoice numbers as INV- plus a six-digit zero-padded sequence, and reports sort them as strings. The sequence will pass 999,999 next year. What do you do?
padStart will not truncate, so new IDs get seven digits and string sorting breaks. Keep the numeric sequence as the source of truth and sort by it; widen the padding in a planned migration (for example to 10 digits) and re-generate display IDs; and add a check, like the one in invoiceNumber, that fails loudly when a value exceeds the width instead of silently producing an unsortable ID.
Key takeaways
Section titled “Key takeaways”padStart(ES2017) adds a repeated, cut-to-fit filler in front of a string until it reaches the target length.- It never shortens a string;
slicefirst when the width is a hard limit. - Length means UTF-16 code units, not visible characters.
- Convert numbers to strings first, handle the minus sign yourself, and prefer
Intl.NumberFormatfor numbers that people read.
Related pages
Section titled “Related pages”- String.padEnd: the same padding at the end of a string.
- String.repeat: build a run of one string, the ES2015 building block for padding.
- Template Literals: assemble padded fields into one line.
- Unicode Support: why
lengthcounts code units, not characters. - JavaScript strings: string basics and common methods.
Official references
Section titled “Official references”- ECMAScript Language Specification,
String.prototype.padStartandStringPad(current draft; first published in ECMAScript 2017) - ECMAScript 2017 Language Specification (ECMA-262, 8th edition)
- TC39 proposal: String padding
- MDN: String.prototype.padStart()
- MDN: Intl.NumberFormat