JavaScriptStrings

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
On this page

Example

#
JavaScript
const codeLine = '    return points   '

console.log(`[${codeLine.trimEnd()}]`)
console.log(`[${codeLine.trim()}]`)
Console
[ return points]
[return points]

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

#
Syntax
string.trimEnd()

More examples

#
Blank lines at the end of a message
JavaScript
const message = 'Hi!\nSubmitting the project.\n\n\n'

console.log(message.split('\n').length)
console.log(message.trimEnd().split('\n').length)
Console
5
2

The three trailing newline characters created three blank lines. After trimEnd(), only the two lines with content were left.

Cleaning up lines while keeping indentation
JavaScript
const lines = ['let a = 1   ', '  let b = 2\t', '']

console.log(lines.map((line) => line.trimEnd()))
Console
['let a = 1', ' let b = 2', '']

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 with trimEnd(). An invisible trailing \n is 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

#

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