JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

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

If you want to remove whitespaces from the end of a string then you can use the two available methods:

  1. String.prototype.trimRight()
  2. String.prototype.trimEnd()

This tutorial will focus on how to use the trimRight() method to remove whitespaces from the righthand side of the string.

The syntax for the trimRight() method is:

let rightTrimmedString = originalString.trimRight();

Note: The trimRight() method does not modify the original string and returns a right-trimmed string.

It is important to note that in JavaScript following characters are considered whitespaces:

  • Spaces
  • Tabs
  • Newline
  • Carriage return
  • Form feed

The following example removes the whitespaces from the left of a string.

let str = "   JavaScript String     ";
let rightTrimmedString = str.trimRight();

console.log('Right-trimmed String');
console.log(rightTrimmedString);
console.log('Original String');
console.log(str);

Output

Right-trimmed String
"   JavaScript String"
Original String
"   JavaScript String     "

Recommended Posts