The String padEnd() method

By

Learn how the JavaScript padEnd() method adds characters to the end of a string until it reaches a target length, using a space or a pad string you provide.

~~~

padEnd() adds characters to the end of a string until the string reaches a length you specify. It was introduced in ES2017, together with padStart(), which does the same at the beginning.

It takes the target length, and optionally the string to pad with:

padEnd(targetLength [, padString])

The default pad string is a space:

'milk'.padEnd(8) //'milk    '

The method returns a new string. The original is untouched, because strings are immutable.

When would you reach for it?

The classic use is aligning columns in text output. Say you’re printing a small price list to the terminal. Names have different lengths, so the prices don’t line up. Pad every name to the same width and they do:

console.log('bread'.padEnd(12) + '1.20')
console.log('milk'.padEnd(12) + '0.99')
console.log('parmigiano'.padEnd(12) + '8.50')

Output:

bread       1.20
milk        0.99
parmigiano  8.50

You can also pad with a visible character, which is nice for table-of-contents style output:

'bread'.padEnd(12, '.') //'bread.......'

What happens with unusual inputs?

If the string is already long enough, you get it back unchanged:

'parmigiano'.padEnd(4) //'parmigiano'

If the pad string doesn’t divide evenly into the space available, it repeats and the last repetition is truncated:

'ab'.padEnd(7, '123') //'ab12312'

An empty pad string adds nothing.

And remember it’s a string method. To pad a number, convert it first with String(0.99).padEnd(6, '0').

Why doesn’t the alignment show up in HTML?

Here’s the pitfall. You pad strings with spaces, the alignment looks right in the terminal, then you render the same strings in a web page and everything is misaligned again.

That’s not padEnd() failing. HTML collapses runs of whitespace into a single space, so your padding disappears.

The fix: render the text inside a <pre> tag, or apply white-space: pre in CSS, and use a monospace font. Space-based alignment only works when every character has the same width and the spaces are preserved.

~~~

Related posts about js: