trim() in JavaScript – Remove Whitespace from a String's Ends
Whenever you use trim() on a string, the method does the following:
- It trims whitespace from both ends of the string.
- 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 asString.prototype.trim()
because it is a method of theString
object'sprototype
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."
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."
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.