JavaScriptStrings

String.prototype.padEnd()

Pads a string on the right with the given text until it reaches the specified length.

Returns
A new string at least targetLength long, padded on the right.
Changes the original
No
On this page

Example

#
JavaScript
const chapters = [
  ['Variables', 3],
  ['Loops', 7],
  ['Functions', 12]
]

for (const [title, page] of chapters) {
  console.log(title.padEnd(12, '.') + page)
}
Console
Variables...3
Loops.......7
Functions...12

Definition and usage

#

The padEnd() method works like padStart(), but it adds characters to the end of the string. It uses spaces by default, and if the string already has at least the desired length, it comes back unchanged.

It comes in handy for aligning text in columns, for example in a results table printed to the console, for creating dotted lines in a table of contents, or for filling fixed-width fields in simple file formats.

The padding text is repeated and trimmed so the result has exactly the desired length. The original string does not change.

Syntax

#
Syntax
string.padEnd(targetLength)
string.padEnd(targetLength, padString)

Parameters

#
  • targetLength

    number

    The target length of the result. When it does not exceed the string's length, the string comes back unchanged.
  • padString

    string, optional

    The text appended at the end, repeated and trimmed to the needed length. Defaults to a space.

More examples

#
A table in the console
JavaScript
const header = 'Student'.padEnd(8) + 'Points'
const rows = ['Mia'.padEnd(8) + 120, 'Jack'.padEnd(8) + 95]

console.log([header, ...rows].join('\n'))
Console
Student Points
Mia 120
Jack 95
A longer padding text
JavaScript
console.log('Loading'.padEnd(14, '.-'))
console.log('OK'.padEnd(1, '*'))
Console
Loading.-.-.-.
OK

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Aligning with spaces only looks right in a fixed-width font, such as in a console. On a web page, use HTML tables or CSS Grid for column layouts instead.
  • Emoji and some symbols count as two length units, so columns containing them can end up misaligned.

Related entries

#

Spotted a mistake or missing an example? Write to us.