Skip to main content

trim() in JavaScript – Remove Whitespace from a String's Ends

Whenever you use trim() on a string, the method does the following:

  1. It trims whitespace from both ends of the string.
  2. It returns the new version of the calling string—without changing the original string.
note
  • A calling string is a string on which you used trim(). So, in " Hello, world! ".trim(), " Hello, world! " is the calling string.
  • Whitespace means the space character, tab, carriage return, new line, form feed, vertical tab, and other Unicode whitespace characters.
  • trim() is sometimes written as String.prototype.trim() because it is a method of the String object's prototype property.

Syntax of the trim() Method

trim() accepts no arguments. Here is the syntax:

callingString.trim();

Example: Use trim() to Remove Whitespace from Both Ends of a String

const myColor = "          I love blue.          ";

// Remove whitespace characters from both ends of myColor:
myColor.trim();

// The invocation above will return: "I love blue."

Try it on CodePen

Note that you can alternatively use replace() and regular expression to implement trim()'s functionality.

Example: Use replace() and Regular Expression to Remove Whitespace from Both Ends of a String

const myName = "          My name is Oluwatobi.          ";

// Trim away the whitespace at both ends of myName:
trimWhitespace(myName);

function trimWhitespace(string) {
return string.replace(/^\s+|\s+$/gm, "");
}

// The invocation above will return: "My name is Oluwatobi."

Try it on CodePen

tip
  • Use trimStart() to remove whitespace only at the beginning of a string.
  • Use trimEnd() to remove whitespace only at the end of a string.

Overview

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

Your support matters: Buy me a coffee to support CodeSweetly's mission of simplifying coding concepts.

Tweet this article