trim() removes whitespace from both ends of a string and returns a new string. It is useful when cleaning user input, form values, and text loaded from files or APIs.
Use trimStart() when only the leading whitespace should be removed and trimEnd() when only the trailing whitespace should be removed. It is also one of the first cleanup steps before toLowerCase() or string validation.
Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.
Quick reference
| Method | Removes |
|---|---|
trim() |
Leading and trailing whitespace |
trimStart() |
Leading only |
trimEnd() |
Trailing only |
Method 1: Remove whitespace with trim()
const text = " hello ";
console.log("trim:", text.trim());You should see one line logging trim: hello.
The result keeps the middle text and removes only the outer whitespace.
Method 2: Remove Only Leading Whitespace
const text = " hello ";
console.log("trim-start:", JSON.stringify(text.trimStart()));You should see one line logging trim-start: "hello ".
Use this when the trailing whitespace should stay in place.
Method 3: Remove Only Trailing Whitespace
const text = " hello ";
console.log("trim-end:", JSON.stringify(text.trimEnd()));You should see one line logging trim-end: " hello".
Use this when the left side must remain unchanged.
Method 4: Clean User Input Before Validation
const name = " Ana ".trim();
console.log(name.length);You should see one line logging 3.
This is a common preprocessing step before checking empty input or saving form data.
Common Questions About JavaScript trim
Does trim remove spaces in the middle of a string?
No. trim() removes whitespace only from the start and end.
What is the difference between trim, trimStart, and trimEnd?
trim() removes both sides. trimStart() removes only the leading whitespace. trimEnd() removes only the trailing whitespace.
Is trim useful for form input?
Yes. It is one of the first steps for cleaning user input before validation or storage.
Does trim remove tabs and newlines?
Yes. trim() removes common whitespace characters at the start and end, including spaces, tabs, and line breaks.
Summary
Use JavaScript trim() to remove whitespace from both ends of a string and trimStart() or trimEnd() when only one side should be cleaned. These methods are especially useful for form input, user names, email addresses, and text normalization before validation or case normalization with toLowerCase().
