References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript string.trimEnd() method

Method JavaScript All modern browsers Updated
Quick answer

The trimEnd() method removes whitespace from the end of a string and returns a new string. " hi ".trimEnd() gives " hi" — only the trailing spaces go. It's the end-only version of trim(); its counterpart trimStart() handles the start.

Overview

trimEnd() strips whitespace from the end of a string, leaving the beginning untouched. Like the other trims, it returns a new string and doesn't modify the original.

It completes the trio with trim() (both ends) and trimStart() (the start). Reach for trimEnd() when leading whitespace is intentional — keeping indentation while removing accidental trailing spaces, which are a common, invisible source of bugs in text comparison and line processing.

Its legacy alias is trimRight(), which still works but is non-standard; use trimEnd(). And remember it only affects the edge — to collapse or remove inner whitespace, use a regex replace().

Syntax

str.trimEnd()

"  hello  ".trimEnd()  // "  hello"

Example

Live example
<pre id="out" style="font:14px ui-monospace,monospace"></pre>
<script>
  const line = 'value   ';

  document.getElementById('out').textContent =
    '[' + line + ']  len ' + line.length + '\n' +
    '[' + line.trimEnd() + ']  len ' + line.trimEnd().length;
</script>

Best practices

  • Use trimEnd() when only trailing whitespace should go and leading whitespace matters.
  • For both ends, use trim(); for the start only, trimStart().
  • Trailing whitespace is invisible and a common bug source — trim it when comparing lines.
  • Prefer trimEnd() over the non-standard alias trimRight().

Frequently asked questions

What does trimEnd() do?
It removes whitespace from the end of a string and returns a new string, leaving the beginning as is.
What is the difference between trimEnd() and trim()?
trimEnd() removes whitespace only from the end; trim() removes it from both ends.
Is trimRight() the same as trimEnd()?
Yes — trimRight() is a legacy alias. Use the standard trimEnd().
How do I trim the start of a string?