JavaScript trimEnd() method


The trimEnd() (also known as trimRight()) method in JavaScript is used to remove whitespace from the end of a string. This includes spaces, tabs, and newline characters. It is particularly useful for cleaning up user input or formatting strings where trailing whitespace may cause issues.

Syntax:

string.trimEnd()

or

string.trimRight()

Both methods perform the same function, and you can use either one based on your preference. However, trimEnd() is the more modern name.

Return Value:

  • Returns a new string with whitespace removed from the end. The original string remains unchanged.

Example 1: Basic Usage

let str = " Hello, World! "; let trimmedStr = str.trimEnd(); console.log(trimmedStr); // " Hello, World!"

In this example, the trailing spaces in the string " Hello, World! " are removed, resulting in " Hello, World!".

Example 2: No Trailing Whitespace

If there is no trailing whitespace, trimEnd() will return the original string unchanged.

let str = "Hello, World!"; let trimmedStr = str.trimEnd(); console.log(trimmedStr); // "Hello, World!" (no change)

Example 3: Whitespace Only

If the string consists entirely of trailing whitespace, trimEnd() will remove all of it.

let str = " "; let trimmedStr = str.trimEnd(); console.log(trimmedStr); // "" (an empty string)

In this case, since the original string contains only spaces, the result is an empty string.

Example 4: Original String Remains Unchanged

The original string is not modified by the trimEnd() method.

let str = " Hello! "; let trimmedStr = str.trimEnd(); console.log(str); // " Hello! " (original string remains unchanged) console.log(trimmedStr); // " Hello!" (new trimmed string)

Example 5: Differences with trim()

While trim() removes whitespace from both ends of a string, trimEnd() only affects the end.

let str = " Hello! "; let trimmedBoth = str.trim(); let trimmedEnd = str.trimEnd(); console.log(trimmedBoth); // "Hello!" (whitespace removed from both ends) console.log(trimmedEnd); // " Hello!" (whitespace removed only from the end)

Summary:

  • The trimEnd() (or trimRight()) method removes whitespace from the end of a string.
  • It returns a new string without modifying the original string.
  • If there is no trailing whitespace, the original string is returned unchanged.
  • If the string consists only of trailing whitespace, an empty string is returned.
  • This method is useful for cleaning up user input or formatting strings where trailing whitespace may cause issues.