GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Home
  • ES6
  • Web
  • JS BOM
  • JS DOM
  • Web API
  • React
  • Node.js
  • Express
  • React Native
  • JavaScript Array Methods
  • JavaScript String Methods
  • Regular Expressions
  • ES Next

This view

  • Original page
  • New address

GeezerVison is showing www.javascripttutorial.net — JavaScript trim() Method

Home » JavaScript String Methods » 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.

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?

Thank you for your feedback!

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.