Skip to content
Announcing the new Pro Zone. Check it out!

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.

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