Lodash _.trim() Method

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 6 Examples + 3 Try It
String utilities

What You’ll Learn

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.

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.

📝 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!"

⚡ Quick Reference

TaskCode patternResult
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 altstr.trim()ES2019 built-in
Mutates?
No

Returns new string

Sides
Both

Start and end

Custom
chars arg

Optional charset

Native
trim()

Built-in equivalent

🧰 Parameters

string Required

The string to trim.

_.trim(input)
chars Optional

Characters to remove from both ends. Defaults to whitespace.

_.trim(url, "/")
return value New string

Trimmed copy; original unchanged.

const clean = _.trim(raw)
inner spaces Preserved

Whitespace between words is never removed by _.trim().

// '  a  b  ' -> 'a  b'

Examples Gallery

Practical _.trim() patterns with copy-ready code and interactive Try It Yourself labs.

📚 Getting Started

Remove surrounding whitespace from a greeting.

Example 1 — Basic whitespace trim

Strip spaces before and after Hello, world!.

javascript
const raw = "   Hello, world!   ";
const trimmed = _.trim(raw);

console.log(trimmed);
// -> "Hello, world!"

console.log(raw.length);
// still 19 (original unchanged)
Try It Yourself

How It Works

_.trim() removes leading and trailing whitespace only.

📈 Practical Patterns

Sanitize forms, compare strings, and chain with other helpers.

Example 2 — Sanitize form input

Trim a username field before validation.

javascript
const username = "  john_doe  ";
const safe = _.trim(username);

console.log(safe);
// -> "john_doe"
Try It Yourself

How It Works

Always trim user text before length checks or database lookups.

Example 3 — Trim before comparison

Ignore accidental edge spaces when comparing strings.

javascript
const a = "   Hello   ";
const b = "Hello";

console.log(_.isEqual(_.trim(a), b));
// -> true
Try It Yourself

How It Works

Trim both sides or one operand so equality reflects user intent.

Example 4 — Trim custom characters

Remove leading and trailing slashes from a path fragment.

javascript
const path = "///api/users///";
const clean = _.trim(path, "/");
// -> "api/users"

How It Works

The second argument defines which characters to strip from each end.

Example 5 — Chain with _.toUpper()

Normalize messy banner text in one expression.

javascript
const messy = "   active   ";
const banner = _.toUpper(_.trim(messy));
// -> "ACTIVE"

How It Works

Trim first, then transform casing—order matters for clean output.

🚀 Beyond the Basics

Native alternatives and related trim helpers.

Example 6 — Native trim() alternative

ES2019 provides String.prototype.trim() for whitespace.

javascript
const raw = "  hello  ";
const native = raw.trim();
const lodash = _.trim(raw);
// both -> "hello"

How It Works

Use native trim() when you only need whitespace removal. Lodash adds optional custom character trimming.

📋 Related string operations

Topic_.trim_.trimStart_.trimEndtrim()
Sides trimmedBothStart onlyEnd onlyBoth (whitespace)
Custom charsYesYesYesNo (whitespace only)
MutatesNoNoNoNo
Best forGeneral cleanupPreserve trailing spacesPreserve leading spacesModern native code

🧠 How _.trim() Works

1

Scan start

Lodash walks from the beginning while characters match the trim set.

Start
2

Scan end

Walks from the end while characters match.

End
3

Slice middle

The remaining substring becomes the result.

Extract
=

Return string

A new string is returned; the original is unchanged.

Done

📝 Notes

  • _.trim() removes from both ends only.
  • Inner whitespace is never removed.
  • Pass chars to trim specific characters instead of whitespace.
  • Use _.trimStart() or _.trimEnd() for one-sided trimming.
  • Strings are immutable—assign the return value.
  • Native String.trim() covers default whitespace in modern engines.

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.

💡 Best Practices

✅ Do

  • Assign the return value—strings are immutable
  • Combine with related helpers when building normalization pipelines
  • Validate user input types before transforming
  • Test Unicode and locale-sensitive strings when relevant
  • Use native string.trim() when Lodash is not already imported

❌ Don’t

  • Expect the original string variable to change in place
  • Assume behavior matches locale-aware toLocaleLowerCase without testing
  • Trim or change casing before checking for empty input when order matters
  • Import all of Lodash for a single call if tree-shaking a tiny bundle
  • Forget to handle null/undefined coercion edge cases

Key Takeaways

01

Both ends

Leading + trailing cleanup.

Basics
02

Inner kept

Middle spaces stay.

Behavior
03

Custom

Optional chars argument.

Advanced
04

Sanitize

Clean form fields.

Pattern
05

Siblings

trimStart / trimEnd.

Related

❓ Frequently Asked Questions

_.trim() removes leading and trailing whitespace (or custom characters) from a string and returns the result.
No. Only characters at the start and end are removed. Inner spaces stay intact.
Yes. Pass a second argument: _.trim(str, '-') removes leading and trailing hyphens.
_.trim() removes from both ends. trimStart and trimEnd target only the beginning or end respectively.
No. Strings are immutable; a new trimmed string is returned.
For basic whitespace trimming in modern JavaScript, native trim() is equivalent. Lodash adds optional custom character trimming and API consistency.
Did you know?

_.trim removes characters from both ends but leaves the middle alone. For one-sided cleanup use _.trimStart() or _.trimEnd().

Practice _.trim() in the Live Editor

Open Try It, run the examples, and experiment with your own strings.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful