String. prototype. trimEnd()
Removes whitespace only from the end of a string, including trailing newline characters.
- Returns
- A new string without whitespace at the end.
- Changes the original
- No
Example
#const codeLine = ' return points '
console.log(`[${codeLine.trimEnd()}]`)
console.log(`[${codeLine.trim()}]`)Definition and usage
#The trimEnd() method returns a new string without whitespace at the end: spaces, tabs, newline characters, and other spacing. The start of the text, including any indentation, stays the same, and the original is not changed.
A typical use case is cleaning up text where the start matters but the end doesn't: indented lines of code, rows read from a file, or content from a textarea field where the user left a few blank lines at the end.
The older name for this method is trimRight(). It works identically, but use trimEnd() in new code, since it pairs consistently with trimStart() and matches the names padStart() and padEnd().
Syntax
#string.trimEnd()More examples
#const message = 'Hi!\nSubmitting the project.\n\n\n'
console.log(message.split('\n').length)
console.log(message.trimEnd().split('\n').length)The three trailing newline characters created three blank lines. After trimEnd(), only the two lines with content were left.
const lines = ['let a = 1 ', ' let b = 2\t', '']
console.log(lines.map((line) => line.trimEnd()))Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Before comparing text from a file or a
textarea, strip trailing newline characters withtrimEnd(). An invisible trailing\nis a common reason why two "identical" strings turn out not to be equal. - If you want to strip specific characters from the end, such as periods,
trimEnd()is not enough. Use a regular expression instead:text.replace(/\.+$/, "").
Related entries
#- String.prototype.trim()Removes whitespace from both ends of a string: spaces, tabs, and newline characters.
- String.prototype.trimStart()Removes whitespace only from the start of a string. The end of the text stays unchanged.
- String.prototype.padEnd()Pads a string on the right with the given text until it reaches the specified length.
- String.prototype.endsWith()Checks whether a string ends with the given text. Returns true or false.
- String.prototype.split()Splits a string into an array of pieces based on a separator: a character, a string, or a regular expression.
Spotted a mistake or missing an example? Write to us.