JavaScript String trim()

The JavaScript trim() method removes whitespace from both ends of a string.

The syntax of trim() is:

str.trim()

Here, str is a string.


trim() Parameter

The trim() method does not take in any parameters.


Return Value from trim()

  • Returns a new string representing the str stripped of whitespace from both ends.

Notes:

  • Whitespace is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
  • The trim() method does not change the original string.

Example: Using trim()

let str = "   foo  ";
console.log(str.trim()); // 'foo'

// trim() removes whitespace only from the edges
let str1 = "  A B C D  ";
console.log(str1.trim()); // 'A B C D'

Output

foo
A B C D