How Lodash escapeRegExp Sanitizes Strings
The _.escapeRegExp function in the Lodash JavaScript
library sanitizes strings by escaping special characters that have
functional meaning in regular expressions. When accepting dynamic user
input to construct a RegExp object, unescaped characters
can alter search logic or trigger syntax errors. This article explains
how _.escapeRegExp identifies and neutralizes these
characters to guarantee that strings are treated purely as literal text
inside regular expressions.
Why Escaping Is Necessary
In JavaScript, regular expressions treat certain characters as metacharacters rather than literal values. These characters include:
^, $, \, .,
*, +, ?, (,
), [, ], {,
}, |
If an unescaped string such as "$10.00 (tax incl.)" is
passed directly into new RegExp(userInput), the JavaScript
engine interprets $, ., (, and
) as pattern-matching operators instead of literal symbols.
This can cause unexpected match results, catastrophic backtracking, or
outright SyntaxError crashes if the pattern forms an
incomplete group or quantifier.
How
_.escapeRegExp Works Internally
Lodash processes input strings through an internal replacement mechanism designed to prepend backslashes to all regex control characters:
- Type Coercion: The method ensures the input is cast to a string. If an empty or non-string input is provided, it handles the value safely to prevent runtime exceptions.
- Detection: Lodash checks the string against an
internal regular expression pattern—commonly defined as
/[\\^$.*+?()[\]{}|]/g—to detect any reserved characters. - Escaping: If special characters are present, Lodash
uses JavaScript's native
.replace()method with a replacement pattern of\\$&. The special token$&represents the matched character, effectively prefixing each occurrence with a backslash (\).
Example Usage
const _ = require('lodash');
const userInput = "function() { return true; }";
const sanitized = _.escapeRegExp(userInput);
console.log(sanitized);
// Output: "function\(\) \{ return true; \}"
// Safely using the sanitized string in a regular expression
const regex = new RegExp(sanitized, 'g');
const documentText = "Check function() { return true; } here.";
const matches = documentText.match(regex);
console.log(matches.length); // 1By neutralizing syntax characters, _.escapeRegExp
ensures that strings used to construct dynamic patterns match the exact
literal input, preventing both regular expression injection bugs and
pattern compilation errors.