trimEnd() removes whitespace from the end of a string and returns a new string. It is useful when you want to clean trailing spaces before saving or comparing user input.
The related methods trimStart() and trim() handle leading whitespace and both ends of the string. If you are cleaning text further, JavaScript trim is the companion topic.
Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.
Remove trailing whitespace with trimEnd()
trimEnd() removes only the whitespace at the end of the string.
const str = " fly better with emirates ";
const newStr = str.trimEnd();
console.log("trimend:", JSON.stringify(newStr));You should see one line logging trimend: " fly better with emirates".
Use this when the trailing whitespace is the only part you want to remove.
Remove leading whitespace with trimStart()
trimStart() removes whitespace from the beginning of the string.
const str = " fly better with emirates ";
const newStr = str.trimEnd().trimStart();
console.log("trimstart:", JSON.stringify(newStr));You should see one line logging trimstart: "fly better with emirates".
This is useful when you need to clean both ends in two explicit steps.
Remove whitespace from both ends with trim()
trim() removes whitespace from both sides in one step.
const str = " fly better with emirates ";
const newStr = str.trim();
console.log("trim:", JSON.stringify(newStr));You should see one line logging trim: "fly better with emirates".
Use this when you need the same cleanup on both ends.
Summary
trimEnd() is the JavaScript method for removing trailing whitespace. Use trimStart() for leading whitespace and trim() when you need to remove spaces from both ends of the string. In form handling and text cleanup, the three methods work together as a small but important set.
