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
targetLengthlong, padded on the right. - Changes the original
- No
Example
#const chapters = [
['Variables', 3],
['Loops', 7],
['Functions', 12]
]
for (const [title, page] of chapters) {
console.log(title.padEnd(12, '.') + page)
}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
#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
#const header = 'Student'.padEnd(8) + 'Points'
const rows = ['Mia'.padEnd(8) + 120, 'Jack'.padEnd(8) + 95]
console.log([header, ...rows].join('\n'))console.log('Loading'.padEnd(14, '.-'))
console.log('OK'.padEnd(1, '*'))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
#- String.prototype.padStart()Pads a string on the left with the given text until it reaches the specified length. Perfect for leading zeros.
- String.prototype.repeat()Returns a new string made up of the given number of copies of the original.
- String.prototype.lengthThe length of a string, i.e. the number of UTF-16 code units. The property is read-only.
- Template literalsText templates in backticks: insert values with ${} and span multiple lines.
Spotted a mistake or missing an example? Write to us.