JavaScript Tutorials

JavaScript String trim()
Syntax & Examples

String.trim() method

The trim() method of the String class in JavaScript removes whitespace from both the beginning and end of a string.


Syntax of String.trim()

The syntax of String.trim() method is:

trim()

This trim() method of String removes whitespace from both the beginning and end of the string.

Return Type

String.trim() returns value of type String.



✐ Examples

1 Using trim() method to remove leading and trailing whitespace

In JavaScript, the trim() method removes whitespace from both the beginning and end of a string.

For example,

  1. We define a string variable str with the value ' Hello World ' which has leading and trailing whitespace.
  2. We use the trim() method to remove the 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.trim();
console.log(newStr);

Output

Hello World

2 Using trim() method on a string with only leading whitespace

In JavaScript, the trim() method can be used to remove leading whitespace from a string.

For example,

  1. We define a string variable str with the value ' Hello' which has leading whitespace.
  2. We use the trim() method to remove the 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';
const newStr = str.trim();
console.log(newStr);

Output

Hello

3 Using trim() method on a string with only trailing whitespace

In JavaScript, the trim() method can be used to remove trailing whitespace from a string.

For example,

  1. We define a string variable str with the value 'Hello ' which has trailing whitespace.
  2. We use the trim() method to remove the 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   ';
const newStr = str.trim();
console.log(newStr);

Output

Hello

Summary

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