How to remove whitespaces from the end of a string in JS?

Overview

In this Answer, we are going to learn how to remove whitespaces from the end of a string.

In Javascript, there is a method called trimEnd() in string.

This method is used to remove the whitespaces only from the ending of a string.

Syntax

String.trimEnd();

Parameter

It doesn’t need any parameters.

Code

var str = `eductive.io `;
console.log("String and it's length before using trimStart method >>> ", str.length);
var trimmedStr = str.trimEnd();
console.log("String and it's length after using trimStart method >>> ", trimmedStr.length);

Code explanation

  • Line 1: Assigned a string which contains whitespaces into the variable called str.

  • Line 2: Print the length of that string.

  • Line 3: After calling the str.trimEnd() method, we store the return value in to another variable called trimmedStr.

  • Line 4: Finally, print the length of the trimmedStr.

We have removed the whitespaces from the ending of the string using trimStart() method so the length of the trimmedStr is reduced.

Free Resources