By the end of this tutorial, you’ll use Lodash’s _.trim() confidently in real string workflows.
01
Core Syntax
Call _.trim(string, [chars]).
02
Both Ends
Strips leading and trailing whitespace by default.
03
Custom Chars
Optional second argument for specific characters.
04
Sanitize Input
Clean form fields before validation.
05
trimStart/End
Use siblings when only one side needs trimming.
06
Production Tips
Know when native trim() is enough.
Fundamentals
What Is _.trim()?
_.trim() removes characters from the start and end of a string. By default it trims whitespace (spaces, tabs, newlines). For one-sided cleanup use _.trimStart() or _.trimEnd().
💡
Beginner tip
Think of _.trim(userInput) as “remove accidental spaces the user typed before and after their answer.” The middle of the string is untouched.
Foundation
📝 Syntax
javascript
_.trim(string, [chars])
Syntax Rules
string — The input string to trim.
chars — Optional. Characters to strip instead of default whitespace.
Return value — New string without leading/trailing matched characters.
Inner whitespace — Preserved—only edge characters are removed.
javascript
import trim from "lodash/trim";
const raw = " Hello, world! ";
const clean = trim(raw);
// -> "Hello, world!"
Cheat Sheet
⚡ Quick Reference
Task
Code pattern
Result
Whitespace
_.trim(str)
Both ends cleaned
Custom chars
_.trim(str, "-")
Strip hyphens
Form input
_.trim(input)
Sanitize field
Compare
_.isEqual(_.trim(a), b)
Ignore edge spaces
One side
_.trimStart(s)
Leading only
Native alt
str.trim()
ES2019 built-in
Mutates?
No
Returns new string
Sides
Both
Start and end
Custom
chars arg
Optional charset
Native
trim()
Built-in equivalent
Reference
🧰 Parameters
stringRequired
The string to trim.
_.trim(input)
charsOptional
Characters to remove from both ends. Defaults to whitespace.
_.trim(url, "/")
return valueNew string
Trimmed copy; original unchanged.
const clean = _.trim(raw)
inner spacesPreserved
Whitespace between words is never removed by _.trim().
// ' a b ' -> 'a b'
Hands-On
Examples Gallery
Practical _.trim() patterns with copy-ready code and interactive Try It Yourself labs.
Native String.trim() covers default whitespace in modern engines.
Wrap Up
Conclusion
_.trim() is the go-to Lodash helper for cleaning edge whitespace and optional custom characters from strings. Use it to sanitize input, normalize comparisons, and prepare text for further Lodash transforms.