trimEnd() in JavaScript – Remove Whitespace from String's End part
Whenever you use trimEnd() on a string, the method does the following:
- It trims whitespace from the end part of the string.
- It returns the new version of the calling string—without changing the original string.
Syntax of the trimEnd()
Method
Section titled “Syntax of the trimEnd() Method”trimEnd()
accepts no arguments. Here is the syntax:
callingString.trimEnd();
Example: Use trimEnd()
to Remove Whitespace from the End part of a String
Section titled “Example: Use trimEnd() to Remove Whitespace from the End part of a String”const myColor = " I love blue. ";
// Remove whitespace characters from the end part of myColor:myColor.trimEnd();
// The invocation above will return: " I love blue."
Note that you can alternatively use replace()
and regular expression to implement trimEnd()
’s functionality.
Example: Use replace()
and Regular Expression to Remove Whitespace from the End part of a String
Section titled “Example: Use replace() and Regular Expression to Remove Whitespace from the End part of a String”const myName = " My name is Oluwatobi. ";
// Trim away the whitespace at the end part of myName:trimEndWhitespace(myName);
function trimEndWhitespace(string) { return string.replace(/\s+$/gm, "");}
// The invocation above will return: " My name is Oluwatobi."