JavaScript String.trim() Method

Shubham Vora Jan 30, 2023
  1. Syntax of JavaScript string.trim():
  2. Example Codes: Use the string.trim() Method to Remove White Space From Both Ends of a String
  3. Example Codes: Use the string.trimRight() Method to Only Remove White Space From the Right Part
JavaScript String.trim() Method

The string.trim() method keeps the original content unchanged while removing the white space character from the start and end parts. On the other hand, string.trimLeft() and string.trimRight() can remove white space from only the left or right part of the string, respectively.

Syntax of JavaScript string.trim():

refString.trim();
refString.trimRight();

Parameter

This method does not take any parameters.

Return

It returns the strings without white space at both ends.

Example Codes: Use the string.trim() Method to Remove White Space From Both Ends of a String

While writing content online, we might include white space at the beginning sentence and the ending part. Using the string.trim() function, we can remove those characters from the string.

In the example below, we have used string.trim() for the string without any parameter.

let str ="  This is a sentence.  ";
console.log(str.trim());

Output:

This is a sentence.

Example Codes: Use the string.trimRight() Method to Only Remove White Space From the Right Part

There might be a requirement for white space at the beginning of a paragraph. So, in this example, we will remove white space characters from the ending part.

In the string, we have used white space on both ends. However, by using the string.trimRight() method, we will remove white space from the right side only.

let str ="  This is a paragraph. ";
let restr = str.trimRight();
console.log(restr);

Output:

  This is a paragraph.

The string.trim() method removes any white space found in the beginning or ending part of a string, including tab and no-break space. This method is supported in most modern browsers.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript String