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.
Syntax of the trim()
Method
Section titled “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
Section titled “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
Section titled “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."