Lodash _.replace() Method

Beginner
⏱️ 8 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 _.replace() confidently in real string workflows.

01

Core Syntax

Call _.replace(string, pattern, replacement).

02

RegExp

Use /pattern/g for all matches.

03

Callbacks

Dynamic replacement functions.

04

Templates

Swap {placeholder} values.

05

Sanitize

Mask sensitive data patterns.

06

Production Tips

Escape regex when matching literals.

What Is _.replace()?

_.replace() searches a string for a pattern (string or RegExp) and substitutes a replacement string or function. It mirrors String.prototype.replace() with lodash’s consistent API.

💡
Beginner tip

Use a RegExp with the g flag to replace all matches—_.replace(text, /foo/g, 'bar'). A string pattern replaces only the first occurrence.

📝 Syntax

javascript
_.replace(string, pattern, replacement)

Syntax Rules

  • string — The source string to search.
  • pattern — String or RegExp to match.
  • replacement — Replacement string or callback function.
  • Return value — New string with substitutions applied.
  • Global flag — Use /pattern/g for all matches with RegExp.
javascript
import replace from "lodash/replace";

const result = replace("Hello world", "world", "lodash");
// -> "Hello lodash"

⚡ Quick Reference

TaskCode patternResult
First match_.replace(s, 'a', 'b')Single substitution
All matches_.replace(s, /a/g, 'b')Global regex
Case insensitive_.replace(s, /hi/i, 'Hello')i flag
Callback_.replace(s, /\d+/g, n => ...)Dynamic replace
Template_.replace(tpl, /{(\w+)}/g, ...)Placeholders
Native altstr.replace(...)Built-in equivalent
Mutates?
No

Returns new string

Pattern
String|RegExp

Flexible matching

Global
/g flag

All occurrences

Native
replace()

Same behavior

🧰 Parameters

string Required

Text to search within.

_.replace(msg, 'old', 'new')
pattern Required

Substring or RegExp to find.

_.replace(s, /\s+/g, '-')
replacement Required

New text or replacer function.

_.replace(s, /x/g, 'y')
return value New string

With replacements applied.

const clean = _.replace(raw, ...)

Examples Gallery

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

📚 Getting Started

Replace a word in a greeting.

Example 1 — Basic substring replacement

Replace the first hello with hi.

javascript
const text = "Hello world, hello universe!";
const result = _.replace(text, "hello", "hi");

console.log(result);
// -> "Hello world, hi universe!"
Try It Yourself

How It Works

String patterns are case-sensitive and replace the first match only.

📈 Practical Patterns

Regex, case flags, and templates.

Example 2 — Case-insensitive regex

Replace all hello regardless of case.

javascript
const text = "Hello world, hello universe!";
const result = _.replace(text, /hello/gi, "hi");

console.log(result);
// -> "hi world, hi universe!"
Try It Yourself

How It Works

gi flags make the pattern global and case-insensitive.

Example 3 — Template placeholders

Swap {name} and {place} with data.

javascript
const tpl = "Hello, {name}! Welcome to {place}.";
const data = { name: "Alice", place: "Wonderland" };

const result = _.replace(tpl, /{([^}]+)}/g, (match, key) => data[key]);
console.log(result);
Try It Yourself

How It Works

Callback replacements read keys from a data object.

Example 4 — Mask sensitive data

Hide SSN patterns in a log line.

javascript
const log = "User: John, SSN: 123-45-6789";
const safe = _.replace(log, /\b\d{3}-\d{2}-\d{4}\b/g, "***-**-****");
// -> "User: John, SSN: ***-**-****"

How It Works

Regex patterns help sanitize structured sensitive data.

Example 5 — URL path rewrite

Replace a numeric user segment with profile.

javascript
const url = "https://example.com/users/12345";
const rewritten = _.replace(url, /\/users\/\d+/, "/profile");
// -> "https://example.com/profile"

How It Works

Regex replaces the first path match in the URL.

🚀 Beyond the Basics

Native replace() alternative.

Example 6 — Native String.replace()

Built-in replace behaves the same for basic cases.

javascript
const text = "foo bar foo";
const native = text.replace(/foo/g, "baz");
const lodash = _.replace(text, /foo/g, "baz");
// both -> "baz bar baz"

How It Works

Use lodash when chaining in functional pipelines.

📋 Related string operations

Topic_.replacereplace()replaceAll()split+join
PatternString|RegExpString|RegExpString|RegExpString only
All matchesRegex /gRegex /gYes (string)Yes
CallbackYesYesNoNo
MutatesNoNoNoNo
Best forLodash pipelinesNative codeSimple globalLiteral strings

🧠 How _.replace() Works

1

Receive string

Source text and pattern.

Input
2

Find matches

String finds first; RegExp uses flags.

Match
3

Apply replacement

Substitute string or invoke callback.

Replace
=

Return result

New string; original unchanged.

Done

📝 Notes

  • String patterns replace only the first occurrence.
  • Use RegExp with g flag for global replacement.
  • Replacement can be a function receiving match details.
  • Does not mutate the original string.
  • For simple literal global replace, replaceAll() (ES2021) works too.
  • Escape regex metacharacters when matching literals—see _.escapeRegExp().

Conclusion

_.replace() handles substring and regex substitutions in lodash pipelines. Choose the right pattern type, use the global flag when needed, and consider callback replacements for dynamic transforms.

💡 Best Practices

✅ Do

  • Assign the return value—strings are immutable
  • Specify radix explicitly when parsing user input
  • Use RegExp /g flag for global replacements
  • Validate counts and inputs before transforming
  • Prefer native methods when lodash is not already imported

❌ Don’t

  • Expect the original string variable to change in place
  • Forget radix when using _.parseInt on user data
  • Use string patterns when you need all matches replaced
  • Import all of Lodash for a single string call
  • Skip NaN checks after parsing

Key Takeaways

01

Pattern

String or RegExp.

Basics
02

Global /g

All occurrences.

Regex
03

Callback

Dynamic values.

Advanced
04

Immutable

New string returned.

Behavior
05

escapeRegExp

Safe literal patterns.

Related

❓ Frequently Asked Questions

Returns a new string with matches of pattern replaced by replacement.
String replaces first match only; RegExp can replace all with the g flag.
Yes—the callback receives match arguments like native replace.
No. Strings are immutable.
replaceAll() (ES2021) is for global string literal replacement; _.replace uses RegExp for the same effect.
Use the i flag: _.replace(s, /hello/i, 'hi').
Did you know?

A string pattern in _.replace replaces only the first match—use a RegExp with /g or replaceAll() to change every occurrence.

Practice _.replace() 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