jsguides

String.prototype.trimEnd()

trimEnd()

The trimEnd() method removes whitespace characters from the end of a string and returns a new string. It’s the standard ES2019 method for right-side trimming, preferred over the legacy trimRight() alias.

Why trimEnd() Over trimRight()?

ES2019 introduced trimEnd() (and trimStart()) as the canonical names, aligning with other string methods like padEnd() and padStart(). The older trimRight() and trimLeft() aliases exist only for backward compatibility. Use trimEnd() in new code for:

  • Consistency with padEnd(), padStart()
  • Clarity — “End” explicitly means the right side, while “Right” could be confused with direction in right-to-left languages
  • Future-proofing — legacy aliases may be deprecated in future ECMAScript versions
console.log("test".trimEnd === "test".trimRight); // true (same method)

Browsers treat trimEnd as the canonical method and alias trimRight to the same function object, so the identity check returns true. Prefer trimEnd() in new code for compatibility with the naming convention used by padEnd() and padStart().

String Immutability

JavaScript strings are immutable — they never change in place. trimEnd() returns a new string, leaving the original untouched. This means you must capture the return value; calling trimEnd() without assigning the result has no observable effect:

const original = "hello   ";
const trimmed = original.trimEnd();

console.log(original); // "hello   " (unchanged)
console.log(trimmed);  // "hello" (new string)

This applies to all string methods. Always capture the returned value.

What gets removed

trimEnd() removes trailing whitespace, including:

  • Spaces ( ) and tabs (\t)
  • Newlines (\n, \r\n, \r)
  • Non-breaking spaces (\u00A0, common in HTML)
  • Other Unicode whitespace characters

Only the end is trimmed — characters in the middle or beginning remain.

const s = "  middle \n";
s.trimEnd(); // "  middle \n" — newline at end removed
s.trim();    // "middle" — whitespace removed from both ends

Use Cases

Trailing whitespace shows up in many real-world situations: log files, user input, API payloads, and configuration values. trimEnd() is the right tool for cleaning up these values when leading characters must stay intact but trailing junk should go. Each case below illustrates a common pattern.

Cleaning file lines

When reading text files, each line often has accidental trailing whitespace:

const lines = [
  "header   ",
  "data one  ",
  "data two\t",
  "footer "
];

const cleaned = lines.map(line => line.trimEnd());
console.log(cleaned);
// ["header", "data one", "data two", "footer"]

This works because map() applies trimEnd() to every element, cleaning up each line individually. The same pattern handles CSV parsing, where trailing tabs or spaces after cell values would otherwise break downstream processing.

Sanitizing user input

Form fields and API responses frequently arrive with padded whitespace. Calling trimEnd() before validation catches these formatting artifacts:

function normalizeInput(value) {
  return value.trimEnd();
}

console.log(normalizeInput("username   "));  // "username"
console.log(normalizeInput("comment\t\n")); // "comment"

The normalizeInput wrapper makes the intent explicit — callers don’t need to remember which trim variant to use. For API endpoints that accept user-submitted text, pairing trimEnd() with the validation step catches padding that would otherwise cause false validation failures.

Preparing for comparison

Trailing whitespace causes subtle bugs in equality checks because two strings that look identical may differ by invisible characters at the tail:

const stored = "password";
const input = "password   ";

if (input.trimEnd() === stored) {
  console.log("Password valid");
}

This guard is especially useful when comparing user-provided values against stored data, such as authentication credentials or lookup keys. The same technique applies to any string comparison where the source of the whitespace is immaterial but would otherwise break the match.

Browser Compatibility

trimEnd() is supported in all modern browsers and Node.js 12+. For older environments, use the legacy trimRight() or a polyfill:

if (!String.prototype.trimEnd) {
  String.prototype.trimEnd = function() {
    return this.replace(/\s+$/, '');
  };
}

Key Behaviors

  • Returns a new string; original is unchanged
  • Removes whitespace only from the end (right side)
  • Returns the original string if no trailing whitespace exists
  • Identical to the legacy trimRight() method

When trimEnd() is the right tool

trimEnd() is especially useful when trailing whitespace is accidental but leading whitespace is meaningful. That comes up in user input, generated text, file parsing, and any situation where indentation or prefixes matter more than the tail padding. It keeps the intent narrow: remove only the characters that are usually accidental at the end and leave the rest of the string alone.

See Also