String.prototype.trim()

Summary: in this tutorial, you’ll learn how to use the JavaScript trim() method to remove whitespace characters from both ends of a string.

Introduction to the JavaScript trim() method #

The String.prototype.trim() returns a new string with whitespace trimmed from the beginning and end of a string.

Here’s how to use the trim() method:

let newString = str.trim();

Note that the trim() method returns a completely new string and doesn’t change the original string.

Image

In JavaScript, the following characters are whitespace:

  • A space character (' ')
  • A tab character (\t)
  • A carriage return character (\r)
  • A new line character. (\n)
  • A vertical tab character. (\v)
  • A form feed character. (\f )

To remove whitespace characters from the beginning or the end of a string only, you use the trimStart() or trimEnd() method.

JavaScript trim() method examples #

Let’s take some examples of using the trim() method.

Basic JavaScript trim() examples #

The following example shows how to use the trim() to remove whitespace from both sides of a string:

let str = '  JavaScript trim  ';
let result = str.trim();

console.log({str});
console.log({result});

Output:

{str: '  JavaScript trim  '}
{result: 'JavaScript trim'}

The following example illustrates how to use the trim() method to remove the leading and trailing newlines from a string:

let str = '\nJavaScript Tutorial\n\n';
let result = str.trim();

console.log({str});
console.log({result});

Output:

{str: '\nJavaScript Tutorial\n\n'}
{result: 'JavaScript Tutorial'}

Chaining with other string methods #

Since the trim() method returns a string, you can chain it with other string methods. For example:

let name = '  John Doe ';
let [firstName, lastName ] = name.trim().split(' ');

console.log({firstName, lastName});

Output:

{firstName: 'John', lastName: 'Doe'}

In this example, we use the trim() method to remove the leading and trailing whitespace from a string and then use the split() method to split the string into two parts.

Summary #

  • Use the trim() to remove whitespace characters from both ends of a string.

Was this helpful?