JavaScript String trim()

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

Example

const message = "   JAVASCRIPT IS FUN    ";

// remove leading and trailing whitespaces const newMessage = message.trim();
console.log(newMessage); // Output: JAVASCRIPT IS FUN

trim() Syntax

The syntax of trim() is:

str.trim()

Here, str is a string.


trim() Parameter

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


trim() Return Value

  • 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
Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community