JavaScript Tutorials

JavaScript String trimEnd()
Syntax & Examples

String.trimEnd() method

The trimEnd() method of the String class in JavaScript removes whitespace from the end of a string. It is an alias for trimRight().


Syntax of String.trimEnd()

There are 2 variations for the syntax of String.trimEnd() method. They are:

1.
trimEnd()

This method removes whitespace from the end of the string.

Returns value of type String.

2.
trimRight()

This method alias for trimEnd(). Removes whitespace from the end of the string.

Returns value of type String.



✐ Examples

1 Using trimEnd() method

In JavaScript, the trimEnd() method removes whitespace from the end of a string.

For example,

  1. We define a string variable str with the value 'Hello World ' which has trailing whitespace.
  2. We use the trimEnd() method to remove the trailing whitespace.
  3. The result is stored in the variable newStr.
  4. We log newStr to the console using the console.log() method.

JavaScript Program

const str = 'Hello World   ';
const newStr = str.trimEnd();
console.log(newStr);

Output

Hello World

2 Using trimRight() method

In JavaScript, the trimRight() method, an alias for trimEnd(), removes whitespace from the end of a string.

For example,

  1. We define a string variable str with the value 'Hello World ' which has trailing whitespace.
  2. We use the trimRight() method to remove the trailing whitespace.
  3. The result is stored in the variable newStr.
  4. We log newStr to the console using the console.log() method.

JavaScript Program

const str = 'Hello World   ';
const newStr = str.trimRight();
console.log(newStr);

Output

Hello World

3 Comparing trimEnd() and trimRight() methods

In JavaScript, both trimEnd() and trimRight() methods perform the same function of removing whitespace from the end of a string.

For example,

  1. We define a string variable str with the value 'Hello World ' which has trailing whitespace.
  2. We use the trimEnd() method to remove the trailing whitespace and store the result in newStr1.
  3. We use the trimRight() method to remove the trailing whitespace and store the result in newStr2.
  4. We log newStr1 and newStr2 to the console using the console.log() method.

JavaScript Program

const str = 'Hello World   ';
const newStr1 = str.trimEnd();
const newStr2 = str.trimRight();
console.log(newStr1); // Hello World
console.log(newStr2); // Hello World

Output

Hello World
Hello World

Summary

In this JavaScript tutorial, we learned about trimEnd() method of String: the syntax and few working examples with output and detailed explanation for each example.