What is the String trim() method in JavaScript?

Overview

The String trim() method is used to remove whitespaces from the start and the end of a string.

Syntax

The trim() method can be declared as shown in the code snippet below:


str.trim()

Parameter

  • str: The string that is to be trimmed.

Return value

The trim() method returns the string str after removing whitespaces from it.

Browser compatibility

The trim() method is supported by the following browsers:

  • Chrome 4
  • Edge 12
  • Firefox 3.5
  • Internet Explorer 10
  • Opera 10.5
  • Safari 5

Code

Consider the code snippet below, which demonstrates the use of the trim() method:

var buff = ' This is Educative. This is trim() example. ';
console.log(buff.trim());

Explanation

A string str is declared in line 1. The trim() method is used in line 3 to remove whitespaces from the start and the end of str.

Free Resources