trim method

The trim method removes spaces from the ends of a string. Most often, this is necessary when the user enters any values: he can accidentally stick extra spaces - and our task is to clear the entered text from them.

Syntax

javascriptstring.trim();

Example

Let's remove trailing whitespaces from a string:

javascriptlet str = '  abcde  ';
console.log(str.trim());

The code execution result (the spaces are gone):

javascript'abcde'

See also

  • the trimEnd method
    that removes whitespaces at the end of a string
  • the trimStart method
    that removes whitespaces at the start of a string