Lodash _.escapeRegExp() 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 confidently use Lodash’s _.escapeRegExp() method in real JavaScript projects.

01

Core syntax

Call _.escapeRegExp(string) before new RegExp().

02

Safe patterns

Turn user text into literal regex fragments.

03

Dynamic search

Build find/replace without syntax errors.

04

vs _.escape()

Know HTML escape vs regex escape.

05

Global replace

Pair with String.replace and flags.

06

Production tips

Never trust unescaped user input in RegExp.

What Is _.escapeRegExp()?

It returns a new string with RegExp metacharacters (like ., *, ?, |, and parentheses) escaped so they are treated as literal characters in a regular expression.

💡
Beginner tip

Import only what you need: import escapeRegExp from "lodash/escapeRegExp" keeps bundles small.

📝 Syntax

javascript
_.escapeRegExp([string=''])
javascript
import escapeRegExp from "lodash/escapeRegExp";

const search = "(cat|dog)";
const safe = escapeRegExp(search);
const regex = new RegExp(safe);

console.log(safe);
// -> "\\(cat\\|dog\\)"

⚡ Quick Reference

TaskCode patternResult
Escape user query_.escapeRegExp(query)Literal-safe pattern
Build RegExpnew RegExp(_.escapeRegExp(s))Valid regex object
Case-insensitivenew RegExp(_.escapeRegExp(s), 'i')Flag still works
Global replacetext.replace(new RegExp(_.escapeRegExp(s), 'g'), '')Remove all matches
Native alternatives.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')Manual escape
Simple substringtext.includes(query)No regex needed
Mutates?
No

Returns new string

Input
String

Coerces null/undefined

Output
Escaped string

Safe for RegExp

Pair with
RegExp / replace

Dynamic matching

🧰 Parameters

Arguments accepted by _.escapeRegExp():

stringPrimary

The input string to transform. Lodash coerces null and undefined to an empty string.

return valueNew string

A new string result. The original input is never mutated.

Examples Gallery

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

Getting Started

Escape special characters so a string can be used literally in a RegExp.

Example 1 — Basic metacharacter escape

Escape parentheses and pipe characters in a search string before building a RegExp.

javascript
const searchString = "(cat|dog)";
const escaped = _.escapeRegExp(searchString);

console.log(escaped);
// -> "\(cat\|dog\)"

const regex = new RegExp(escaped);
console.log(regex.test("(cat|dog)"));
// -> true
Try It Yourself

How It Works

_.escapeRegExp() adds backslashes so (, ), and | are literals, not grouping or alternation operators.

Practical Patterns

Build safe dynamic patterns from user-provided or external data.

Example 2 — User input search pattern

Wrap user input in a RegExp without syntax errors when the query contains regex characters.

javascript
const userInput = "(user input)";
const escapedInput = _.escapeRegExp(userInput);
const pattern = new RegExp(escapedInput);

console.log(pattern.source);
// -> "\(user input\)"
Try It Yourself

How It Works

Without escaping, parentheses in user input would create invalid or unintended capture groups.

Example 3 — Search and replace

Replace literal $ and ^ characters using an escaped search string.

javascript
const text = "Replace $ and ^ with _";
const searchString = "$^";
const escaped = _.escapeRegExp(searchString);
const regex = new RegExp(escaped, "g");

const replaced = text.replace(regex, "_");
console.log(replaced);
// -> "Replace _ and _ with _"
Try It Yourself

How It Works

Metacharacters $ and ^ are escaped so they match literally in the text.

Example 4 — Complex special-character string

Escape a string containing many regex metacharacters at once.

javascript
const special = "This$[is]a*special^string";
const escaped = _.escapeRegExp(special);

console.log(escaped);

How It Works

Lodash handles the full set of RegExp metacharacters in one call.

Beyond the Basics

Case-insensitive matching and filter pipelines with escaped terms.

Example 5 — Case-insensitive dynamic filter

Filter an array with a user term using an escaped, case-insensitive RegExp.

javascript
const items = ["Apple Pie", "Banana", "Apricot"];
const term = "ap";
const regex = new RegExp(_.escapeRegExp(term), "i");

const matches = items.filter((item) => regex.test(item));
console.log(matches);
// -> ["Apple Pie", "Apricot"]

How It Works

Escaping keeps the term literal while the i flag enables case-insensitive matching.

Example 6 — When to use String.includes()

For simple substring checks, native methods avoid RegExp entirely.

javascript
const haystack = "Hello (world)";
const needle = "(world)";

// Simple check — no RegExp needed:
console.log(haystack.includes(needle));
// -> true

// Lodash escape only needed when using RegExp:
const regex = new RegExp(_.escapeRegExp(needle));
console.log(regex.test(haystack));
// -> true

How It Works

Prefer includes() for literal substring search; use _.escapeRegExp() when you need regex flags or pattern APIs.

🧠 How _.escapeRegExp() Works

1

Receive input string

Lodash reads the string (or coerces null/undefined to "").

Input
2

Scan metacharacters

Characters like ., *, ?, (, ), |, [, ], \, ^, and $ are identified.

Scan
3

Insert backslashes

Each special character is prefixed with a backslash for literal matching.

Escape
=

Return safe string

Use the result inside new RegExp() or replace() without breaking syntax.

Output

📝 Notes

  • _.escapeRegExp() is for regular expressions, not HTML escaping.
  • Always escape before passing user text into new RegExp().
  • For simple “contains” checks, includes() may be enough.
  • Escaping does not prevent ReDoS—still validate input length and complexity.
  • The returned string is meant to be used inside a RegExp, not displayed to users.
  • Pair with _.escape() when rendering matched text as HTML.

Conclusion

_.escapeRegExp() is a practical Lodash string helper for everyday JavaScript tasks. Use the examples above as starting points in your own code.

💡 Best Practices

✅ Do

  • Escape user input before new RegExp()
  • Use with replace() when removing literal special chars
  • Keep search terms in a variable, escape once, reuse
  • Pair with case-insensitive flags when appropriate
  • Document why escaping is required in search utilities

❌ Don’t

  • Confuse _.escapeRegExp() with _.escape() for HTML
  • Pass raw user strings into RegExp constructors
  • Assume escaping alone prevents ReDoS attacks
  • Double-escape already escaped strings
  • Use RegExp when includes() is sufficient

Key Takeaways

Knowledge Unlocked

Five things to remember about _.escapeRegExp()

5
Core concepts
02

User input

Always escape first.

Security
03

new RegExp()

Build dynamic patterns.

Pattern
04

vs escape

Regex vs HTML.

Compare
05

includes()

Simpler alternative.

Native

❓ Frequently Asked Questions

It returns a new string with RegExp metacharacters (like ., *, ?, |, and parentheses) escaped so they are treated as literal characters in a regular expression.
Whenever you build a RegExp from user input, database text, or any string that may contain regex syntax. Escaping prevents syntax errors and accidental pattern logic.
No. Strings are immutable in JavaScript. _.escapeRegExp() always returns a new escaped string.
_.escape() converts HTML entities (&, <, >, etc.). _.escapeRegExp() escapes characters that have special meaning inside regular expressions.
Yes for simple substring checks. Use _.escapeRegExp() when you need RegExp features such as global replace, case-insensitive flags, or anchored matching.
Lodash coerces missing values to an empty string, so _.escapeRegExp(null) returns "".
Did you know?

_.escapeRegExp() prefixes regex metacharacters with backslashes so a user-provided string can be used literally inside new RegExp() without breaking the pattern.

Practice _.escapeRegExp() in the Live Editor

Open the Try It editor and run the examples with your own input.

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