The JavaScript string.trimEnd() method
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 and is kept in the spec only for web compatibility; 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
<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 legacy aliastrimRight().
Frequently asked questions
What does trimEnd() do?
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()?
trimRight() is a legacy alias. Use the standard trimEnd().