JavaScript String trimEnd() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Instance method

What You’ll Learn

String.prototype.trimEnd() returns a new string with whitespace removed from the end only (same API as MDN String.prototype.trimEnd()). Learn the trimRight alias, how it differs from trim() / trimStart(), five examples, and try-it labs.

01

Kind

Instance method

02

Returns

New string

03

Parameters

None

04

Removes

End only

05

Alias

trimRight()

06

Baseline

Widely available

Introduction

Sometimes you need to drop trailing spaces or newlines but keep leading indentation. That is exactly what trimEnd() does — clean the right side only.

After trim() was standardized, engines also had a non-standard trimRight(). The standard name is trimEnd() (to match padEnd()), and trimRight remains as an alias of the same function for compatibility.

💡
Beginner tip

Prefer trimEnd() in new code. Use plain trim() when both ends should be cleaned (typical form fields).

This page is part of JavaScript String Methods. Related topics include trim() and padEnd().

Understanding the trimEnd() Method

str.trimEnd() builds a new string with trailing whitespace removed. Leading whitespace and middle spaces stay unchanged.

  • Returns a new string — the original is unchanged.
  • Takes no parameters.
  • Only the end (right side) is cleaned.
  • trimRight is the same function (alias).

📝 Syntax

General form of String.prototype.trimEnd:

JavaScript
str.trimEnd()
str.trimRight()  // alias — same function

Parameters

None.

Return value

A new string representing str stripped of whitespace from its end. If there is no trailing whitespace, a new string is still returned (essentially a copy).

Exceptions

None for normal string values.

Aliasing

trimRight and trimEnd refer to the exact same function object. In some engines, String.prototype.trimRight.name === "trimEnd".

Common patterns

JavaScript
"   Hello world!   ".trimEnd();  // "   Hello world!"
"   foo  ".trimEnd();            // "   foo"
"\t hi \n".trimEnd();            // "\t hi"
"no-spaces".trimEnd();           // "no-spaces"

⚡ Quick Reference

GoalCode
Trim the endstr.trimEnd()
Old alias namestr.trimRight()
Trim both endsstr.trim()
Trim the startstr.trimStart()
Drop trailing newlineline.trimEnd()

🔍 At a Glance

Four facts to remember about String.trimEnd().

Returns
string

New trimmed text

Side
end

Right side only

Alias
trimRight

Same function

Mutates
no

Immutable

📋 trimEnd() vs trim() vs trimStart()

trimEnd()trim()trimStart()
Removes fromEnd onlyBoth endsStart only
AliastrimRight()trimLeft()
" hi "" hi""hi""hi "
Best forTrailing spaces / newlinesForm fieldsKeep trailing pad

Examples Gallery

Examples follow MDN String.trimEnd() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

MDN demos for trimming the end only.

Example 1 — Basic trimEnd()

MDN Try it demo: trailing spaces removed; leading spaces kept.

JavaScript
const greeting = "   Hello world!   ";

console.log(greeting);
// Expected output: "   Hello world!   ";

console.log(greeting.trimEnd());
// Expected output: "   Hello world!";
Try It Yourself

How It Works

Only the spaces after ! are removed. The three spaces before Hello remain.

Example 2 — Length After trimEnd()

MDN Using trimEnd() demo — watch the length change.

JavaScript
let str = "   foo  ";

console.log(str.length); // 8

str = str.trimEnd();
console.log(str.length); // 6
console.log(str);        // '   foo'
Try It Yourself

How It Works

Two trailing spaces are removed (8 → 6). The three leading spaces stay, so the visible text is still indented.

🔧 Details & Patterns

Alias, family compare, and trailing newlines.

Example 3 — trimRight Alias

Both names call the same function.

JavaScript
const padded = "  hi  ";

console.log(padded.trimEnd() === padded.trimRight());
// true

console.log(String.prototype.trimEnd === String.prototype.trimRight);
// true

console.log(String.prototype.trimRight.name);
// "trimEnd" (in many engines)
Try It Yourself

How It Works

Write trimEnd in new tutorials and apps. Older code may still say trimRight — it is fine, just an alias.

Example 4 — Family Side-by-Side

Same input, three different trim methods.

JavaScript
const padded = "  hi  ";

console.log(JSON.stringify(padded.trimEnd()));
// "  hi"

console.log(JSON.stringify(padded.trim()));
// "hi"

console.log(JSON.stringify(padded.trimStart()));
// "hi  "
Try It Yourself

How It Works

Pick the method that matches which edge(s) you want cleaned. Default to trim() for user input.

Example 5 — Keep Indent, Drop Trailing Newline

Practical pattern: clean line endings without losing indentation.

JavaScript
function cleanLine(line) {
  return line.trimEnd();
}

const indented = "    console.log(1);\n";
const cleaned = cleanLine(indented);

console.log(JSON.stringify(cleaned));
// "    console.log(1);"

console.log(cleaned.startsWith("    ")); // true — indent kept
console.log(cleaned.endsWith("\n"));     // false
Try It Yourself

How It Works

Using full trim() here would also remove the leading spaces and break indentation. trimEnd() only removes the trailing newline.

🎯 Common Use Cases

  • Preserve indentation — strip trailing spaces/newlines on code lines.
  • CSV / fixed-width cleanup — remove end padding, keep start alignment.
  • Log / file lines — drop \r / \n at the end only.
  • Not for form fields — usually prefer trim() (both ends).
  • Not mid-string spaces — use replace / regex for those.

🧠 How trimEnd() Works

1

Scan from the end

Walk backward while characters are whitespace.

End
2

Stop at first non-space

Everything before that point is kept, including leading spaces.

Keep
3

Drop the trailing run

Spaces, tabs, and line breaks at the end are removed.

Trim
4

Return a new string

Original string is never modified.

📝 Notes

  • Always returns a new string — assign it if you need the result.
  • Leading whitespace is intentionally kept.
  • trimRight is an alias — prefer trimEnd in new code.
  • Does not change spaces in the middle of the string.
  • Named to mirror padEnd() after standardization.

Browser & Runtime Support

String.prototype.trimEnd() is Baseline Widely available — supported across modern browsers since January 2020.

Baseline · Widely available

String.trimEnd()

Safe for production in browsers and runtimes (Node.js, Deno, Bun). Prefer trimEnd() over the trimRight() alias in new code.

Universal Widely available
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
trimEnd() Excellent

Bottom line: Use String.trimEnd() to remove trailing whitespace while keeping leading spaces. Use trim() for both ends and trimStart() for the start only.

Conclusion

String.prototype.trimEnd() cleans the right side of a string — perfect when indentation must stay. Prefer it over trimRight(), and use trim() when both ends should go.

Continue with trim(), padEnd(), or the String methods hub.

💡 Best Practices

✅ Do

  • Use trimEnd when leading spaces must remain
  • Prefer trimEnd over trimRight in new code
  • Use trim() for typical form input
  • Assign the return value — original stays padded
  • Pair mentally with padEnd naming

❌ Don’t

  • Expect leading spaces to disappear
  • Use it when both ends should be cleaned
  • Assume mid-string spaces are collapsed
  • Forget tabs and newlines also count as whitespace
  • Mutate expectations without assignment

Key Takeaways

Knowledge Unlocked

Five things to remember about String.trimEnd()

End only — leading spaces kept, trimRight is an alias.

5
Core concepts
📏 02

Removes

end only

Role
🔄 03

Alias

trimRight

Compat
🔍 04

Keeps

leading spaces

Rule
05

Mutates

no

Immutable

❓ Frequently Asked Questions

String.prototype.trimEnd() returns a new string with whitespace removed from the end (right side) only. Leading whitespace is kept. The original string is not changed.
Yes. trimRight() is an alias of trimEnd() — they are the same function. Prefer trimEnd() for consistency with padEnd().
Whitespace includes spaces, tabs, newlines, and other white space characters plus line terminators (same rules as trim()).
trim() cleans both ends. trimStart() removes only from the start. trimEnd() removes only from the end.
No. Strings are immutable. trimEnd() always returns a new string — even when there was nothing to remove.
When you must keep leading indentation or padding but want to drop trailing spaces or newlines — for example cleaning lines while preserving indent.
Did you know?

The name trimEnd was chosen to match padEnd. trimRight stayed as an alias so older pages and libraries keep working — in many engines even trimRight.name reports "trimEnd".

More String Methods

Return to the hub for slice, trim, replace, and more.

String methods hub →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful