Skip to content

String.prototype.padEnd(): align text columns (ES2017)

  • What padEnd(targetLength, padString) returns and how it differs from padStart.
  • How to build left-aligned columns, dot leaders and fixed-width records.
  • Why you must pair it with slice when a field has a hard width.
  • Why length is not the same as the width you see on screen.

TL;DR: str.padEnd(targetLength, padString = " ") returns a new string of at least targetLength UTF-16 code units, with padString repeated (and cut to fit) after the original text. A string that is already long enough comes back unchanged. It was added in ECMAScript 2017 together with padStart(), and the two share one algorithm in the specification.

Plain text still matters: order confirmation emails, CLI output, log lines and fixed-width files for older batch systems. All of them need a label filled out to a column. Before ES2017 that meant concatenating a filler and slicing it back.

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: concatenate a repeated filler, then cut it back.
const label = 'Subtotal';
console.log((label + '..........').slice(0, 12) + '|');
console.log((label + ' '.repeat(12)).slice(0, 12) + '|'); // ES2015 repeat helped a little
// ES2017
console.log(label.padEnd(12, '.') + '|');
console.log(label.padEnd(12) + '|');

Output:

Subtotal....|
Subtotal |
Subtotal....|
Subtotal |

The old pattern hides a second job: slice(0, 12) also truncated long labels. padEnd only pads, which matters in the realistic example below.

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

padEnd uses exactly the same rules as padStart (covered step by step on the padStart() page): targetLength is converted with ToLength, a string that is long enough is returned unchanged, the default filler is a space, an empty filler returns the original, and the filler is repeated and cut to fit. The only difference is placement.

console.log('abc'.padEnd(8, '12') + '|'); // filler repeats and is cut to fit
console.log('Wireless keyboard'.padEnd(8) + '|'); // never truncates
console.log('abc'.padEnd(6, '') + '|'); // empty filler: unchanged
console.log('café'.padEnd(6, '.') + '|'); // precomposed é: 4 code units
console.log('café'.padEnd(6, '.') + '|'); // e + combining accent: 5 code units
console.log('茶'.padEnd(4, '.') + '|'); // one code unit, but two columns wide in a terminal
console.log('1.5'.padEnd(4, '0')); // string padding is not number formatting

Output:

abc12121|
Wireless keyboard|
abc|
café..|
café.|
茶...|
1.50

The two café lines look the same but get different padding, because one uses a single precomposed character and the other uses e plus a combining accent. The 茶 line shows a separate problem: terminals draw most CJK characters two columns wide, so the bar no longer lines up even though the code-unit count is right. padEnd measures code units, not what the reader sees. Normalize with normalize('NFC') before padding, and see Unicode Support for counting user-visible characters.

The last line happens to look like money formatting, but '12.345'.padEnd(4, '0') returns '12.345' unchanged. Use toFixed or Intl.NumberFormat for decimals.

OrdersPortal sends a plain-text version of every receipt. Item names are left-aligned with padEnd and cut when too long; amounts are right-aligned with padStart:

// receipt.mjs - plain-text order receipt for OrdersPortal emails and the CLI.
// Fit text to an exact width: cut long values, pad short ones.
// padEnd alone never shortens a string, so slice first.
export function fit(text, width, fill = ' ') {
const value = String(text);
return value.length > width
? value.slice(0, width - 1) + '…'
: value.padEnd(width, fill);
}
export function receipt(order, width = 36) {
const amountWidth = 10;
const nameWidth = width - amountWidth;
const money = (n) => n.toFixed(2).padStart(amountWidth); // right-align: see padStart
const lines = [`Order ${order.id}`, '-'.repeat(width)];
for (const item of order.items) {
lines.push(fit(`${item.qty} x ${item.name}`, nameWidth) + money(item.qty * item.price));
}
const subtotal = order.items.reduce((sum, i) => sum + i.qty * i.price, 0);
lines.push('-'.repeat(width));
lines.push(fit('Subtotal ', nameWidth, '.') + money(subtotal));
lines.push(fit('Shipping ', nameWidth, '.') + money(order.shipping));
lines.push(fit('Total ', nameWidth, '.') + money(subtotal + order.shipping));
return lines.join('\n');
}
console.log(receipt({
id: 'INV-000123',
shipping: 4.5,
items: [
{ qty: 1, name: 'Wireless keyboard', price: 49.99 },
{ qty: 2, name: 'USB-C cable, braided, 2 m, gray', price: 9.5 },
],
}));

Output:

Order INV-000123
------------------------------------
1 x Wireless keyboard 49.99
2 x USB-C cable, braided,… 19.00
------------------------------------
Subtotal ................. 68.99
Shipping ................. 4.50
Total .................... 73.49

Without the slice branch in fit, the long cable name would push its amount out of the column. (The slice in fit can still split an emoji in half; for names that may contain emoji, cut at a grapheme boundary as shown on the Unicode page. Real money code would also use integer cents rather than floating-point sums.)

The same rule applies to fixed-width files, where every field must be exactly its width:

// Fixed-width record for a legacy batch import: every field has an exact width.
const fields = [
['INV-000123', 12],
['Ada Example', 20],
['US', 2],
];
const record = fields.map(([value, width]) => value.slice(0, width).padEnd(width)).join('');
console.log(JSON.stringify(record), record.length);

Output:

"INV-000123 Ada Example US" 34
  • Assuming it truncates. A value longer than targetLength comes back whole and breaks the column or record. Use value.slice(0, width).padEnd(width) when the width is fixed.
  • Using it for decimals. '1.5'.padEnd(4, '0') looks right by accident; '1.505'.padEnd(4, '0') does not round. Use toFixed or Intl.NumberFormat.
  • Byte-based formats. Fixed-width files are often specified in bytes, while padEnd counts UTF-16 code units. 'é' is one code unit but two UTF-8 bytes. Measure with new TextEncoder().encode(value).length when the target is bytes.
  • Aligning in HTML. Trailing spaces collapse in HTML and do not align in proportional fonts. Use a table or CSS grid; keep padEnd for monospaced text.
  • Trailing whitespace that gets stripped. Editors, email clients and some CSV tools trim trailing spaces. Pad with a visible character, or pad the left column only.
Need Use
Left-aligned label or column in monospaced text padEnd(width)
Dot leaders (Subtotal .....) padEnd(width, '.')
Exact-width field slice(0, width).padEnd(width)
Right-aligned numbers, zero-padded IDs padStart()
Decimal places or localized numbers toFixed() or Intl.NumberFormat
Layout in a web page HTML tables or CSS, not spaces

According to MDN’s browser compatibility data, padEnd 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; core-js provides a polyfill for legacy browsers.

1. What is the difference between padStart and padEnd? Only where the filler goes: before the text for padStart, after it for padEnd. Both use the same specification algorithm, the same defaults (a space) and the same “never truncate” rule.

2. How do you produce a field that is always exactly 20 characters? value.slice(0, 20).padEnd(20). padEnd alone returns longer values unchanged.

3. Why might a column built with padEnd look misaligned in a terminal? padEnd counts UTF-16 code units. Emoji take two units, decomposed accents add a unit, and wide East Asian characters occupy two terminal columns while counting as one unit.

4. Senior scenario: OrdersPortal must export orders to a partner’s fixed-width file format, specified as 120 bytes per line in UTF-8. Customer names include accents and emoji. How do you build each line? Treat the spec as bytes, not string length. Normalize names to NFC, then cut each field at a grapheme boundary while its UTF-8 byte length (TextEncoder) fits, and pad with ASCII spaces, which are one byte each, so the byte count becomes exact. Validate every line’s encoded length before writing, and add tests with accented and emoji names. If the partner cannot accept non-ASCII bytes at all, agree on a transliteration rule rather than padding broken text.

  • padEnd (ES2017) adds a repeated, cut-to-fit filler after a string until it reaches the target length.
  • It never truncates: pair it with slice for exact widths.
  • It counts UTF-16 code units, not bytes, graphemes or terminal columns.
  • Use it for monospaced text; use number formatters for numbers and CSS for web layout.