Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท String

String.prototype.trimEnd()

Reference for JavaScript String.prototype.trimEnd(): remove whitespace and newlines from the end of a string, including the trimRight() alias, with examples.

The trimEnd() method returns a copy of a string with whitespace removed from the end only. Leading whitespace stays. Whitespace means the same set of characters as for trim(): spaces, tabs, line terminators, the non-breaking space and other Unicode space characters.

Typical uses are cleaning the trailing newline from a line of text, removing trailing spaces before saving or comparing, and tidying generated output without losing indentation.

JavaScript
"  hello  ".trimEnd(); // "  hello"

Try it

JS Removing trailing newlines and spaces

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Cleaning every line

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
string.trimEnd()

This method takes no parameters.

Return value: a new string with trailing whitespace and line terminators removed.

Exceptions: none for strings.

Usage notes

  • Alias: trimRight() is the older name for the same function. Prefer trimEnd(): "right" is the wrong side for right-to-left languages.
  • Same whitespace set as trim(). The zero-width space U+200B is not considered whitespace and stays.
  • Line endings: it removes \n, \r\n and a lone \r at the end, which makes it handy after reading lines from text. Only trailing ones are removed, so inner newlines are kept.
  • Multiple blank lines at the end are all removed, because every trailing whitespace character is stripped.
  • Not for other characters. To remove a trailing slash or comma use a regular expression such as /\/+$/, as in the second example.
  • Immutable: the original string is unchanged; use the return value.
  • Empty and blank strings give "".
  • Non-strings lack this method. Convert with String(value) first.

Browser support

String.prototype.trimEnd() is available in all current browsers. It was added in ES2019, so check a compatibility table for very old browsers.