Skip to content

String.prototype.padStart(): fixed-width text (ES2017)

  • 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.

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().

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 space
console.log(`[${'7'.padStart(3)}]`);

Output:

000042
000042
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.

// Fragment: signature
str.padStart(targetLength)
str.padStart(targetLength, padString)

The specification (StringPaddingBuiltinsImpl and StringPad) defines these steps:

  1. Convert this to a string, and targetLength to an integer with ToLength (so NaN and negative values become 0).
  2. If targetLength is not greater than the string’s length, return the string unchanged. The filler is not even converted.
  3. Use " " when padString is undefined; otherwise convert it with ToString. If it is the empty string, return the original string.
  4. Repeat the filler, cut it to targetLength - length code units, and put it in front.
console.log('abc'.padStart(10, '123')); // filler repeats, then is cut to fit
console.log('abc'.padStart(6, '12345')); // filler cut to 3 code units
console.log('abc'.padStart(2, '0')); // already long enough: unchanged, never truncated
console.log('abc'.padStart(6, '')); // empty filler: unchanged
console.log('abc'.padStart(-1, '0')); // negative or NaN length counts as 0
console.log('5'.padStart('3', 0)); // arguments are converted: '3' -> 3, 0 -> '0'
console.log('😀'.length, '😀'.padStart(3, '*')); // length counts UTF-16 code units
console.log(String(-5).padStart(3, '0')); // the sign is just another character
try {
'x'.padStart(Infinity, '-');
} catch (error) {
console.log(error.constructor.name, '-', error.message);
}
console.log('x'.padStart(Infinity, '')); // empty filler returns before building anything

Output:

1231231abc
123abc
abc
abc
abc
005
2 *😀
0-5
RangeError - Invalid string length
x

The 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.

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 order
console.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' ]
••••••••••••4242
09:05 23:59
-007 007
5.00
129.50
1024.99

Zero 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().

  • Expecting truncation. '1234567'.padStart(6, '0') returns all seven characters. If the width is a hard limit, slice first and decide which end to keep.
  • Calling it on a number. (42).padStart(6, '0') throws TypeError: 42.padStart is not a function. Use String(42) first.
  • Padding negative numbers. String(-5).padStart(3, '0') gives 0-5. Pad the absolute value and add the sign back, or use Intl.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. padStart knows nothing about decimals, grouping or locales.

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 strings
const 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()

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.

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.

  • 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; slice first 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.NumberFormat for numbers that people read.