Skip to main content

trimEnd() in JavaScript – Remove Whitespace from String's End part

Whenever you use trimEnd() on a string, the method does the following:

  1. It trims whitespace from the end part of the string.
  2. It returns the new version of the calling string—without changing the original string.
note
  • A calling string is a string on which you used trimEnd(). So, in " Hello, world! ".trimEnd(), " Hello, world! " is the calling string.
  • Whitespace means the space character, tab, carriage return, new line, form feed, vertical tab, and other Unicode whitespace characters.
  • trimRight() is an alias for trimEnd(). So, you can technically use the two methods to trim whitespace from a string's end part. However, it's best practice to use trimEnd().
  • trimEnd() is sometimes written as String.prototype.trimEnd() because it is a method of the String object's prototype property.

Syntax of the trimEnd() Method

trimEnd() accepts no arguments. Here is the syntax:

callingString.trimEnd();

Example: Use trimEnd() to Remove Whitespace from the End part of a String

const myColor = "          I love blue.          ";

// Remove whitespace characters from the end part of myColor:
myColor.trimEnd();

// The invocation above will return: " I love blue."

Try it on CodePen

Note that you can alternatively use replace() and regular expression to implement trimEnd()'s functionality.

Example: Use replace() and Regular Expression to Remove Whitespace from the End part of a String

const myName = "          My name is Oluwatobi.          ";

// Trim away the whitespace at the end part of myName:
trimEndWhitespace(myName);

function trimEndWhitespace(string) {
return string.replace(/\s+$/gm, "");
}

// The invocation above will return: " My name is Oluwatobi."

Try it on CodePen

tip
  • Use trimStart() to remove whitespace only at the beginning of a string.
  • Use trim() to remove whitespace from both ends of a string.

Overview

The JavaScript trimEnd() method trims whitespace only at the end of a string.

Your support matters: Buy me a coffee to support CodeSweetly's mission of simplifying coding concepts.

Tweet this article