Advanced JavaScript Regex: RegExp.escape, Modifiers, Practical Patterns and Catastrophic Backtracking
Beyond regex basics: escaping user input with RegExp.escape, inline modifiers and duplicate named groups (ES2025), Unicode normalization, tested recipes for common tasks, why validating emails and URLs with regexes goes wrong, catastrophic backtracking and ReDoS, and how to keep patterns readable.
kvi5hnuCode Sprout team member6 min readOn this page
You can now write patterns (article 80) and use them with every method (article 81). This last regex article covers the newest features, a set of practical recipes, and the two ways regexes most often cause real trouble: unescaped user input and catastrophic backtracking.
Escaping user input with RegExp.escape
Building a regex from user input without escaping it is a bug and sometimes a security problem: the user's . or + becomes regex syntax.
const search = "1+1";
console.log(new RegExp(search).test("11")); // + became a quantifier!
console.log(new RegExp(RegExp.escape(search)).test("11"));
console.log(new RegExp(RegExp.escape(search)).test("is 1+1 2?"));
console.log(RegExp.escape("price (USD): $5.00?"));
true
false
true
\x70rice\x20\(USD\)\x3a\x20\$5\.00\?
RegExp.escape (ES2025) escapes every character that could have special meaning anywhere in a pattern, including some you might not expect (a leading letter or digit becomes \x.. so it can't merge with a preceding \1 or \c; spaces and some punctuation are hex-escaped). The result is safe to insert into any position of a larger pattern:
function highlight(text, term) {
const re = new RegExp(RegExp.escape(term), "gi");
return text.replace(re, (match) => `[${match}]`);
}
console.log(highlight("C++ and c++ (not C#)", "c++"));
[C++] and [c++] (not C#)
In environments without RegExp.escape, the classic hand-written version is text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"). And if you don't need regex features at all, plain string methods (includes, replaceAll with a string) need no escaping.
Inline modifiers (ES2025)
Flags apply to the whole pattern. Modifiers apply a flag to just part of it with (?flags:...), or turn one off with (?-flags:...). The supported flags are i, m and s:
const command = /^(?i:git) Commit$/; // "git" in any case, "Commit" exactly
console.log(command.test("GIT Commit"), command.test("git commit"));
true false
Duplicate named groups (ES2025)
The same group name may now appear in different alternatives, since only one of them can match. That makes it easy to accept several formats and read the result the same way:
const yearPattern = /(?<year>\d{4})-\d{2}|\d{2}\/(?<year>\d{4})/;
console.log("2026-11".match(yearPattern).groups.year, "11/2027".match(yearPattern).groups.year);
2026 2027
Unicode text: normalize first
The same visible text can be stored in different ways: é may be one code point (U+00E9) or e plus a combining accent (U+0301). A regex compares code points, so it sees them as different (article 7). Normalize before matching user text:
const composed = "caf\u00e9";
const decomposed = "cafe\u0301";
console.log(composed === decomposed, /café/.test(decomposed), /café/.test(decomposed.normalize("NFC")));
const slugify = (s) =>
s.normalize("NFKD").replace(/\p{M}/gu, "") // split accents off, then drop them
.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
console.log(slugify(" Crème Brûlée: The Recipe! "));
false false true
creme-brulee-the-recipe
\p{M} matches "marks" such as combining accents, so NFKD plus removing marks is a common way to make accent-insensitive slugs and search keys.
Practical recipes
Each recipe below was run against the sample inputs shown. Treat them as starting points and test them against your own data.
// collapse whitespace
console.log(" too many spaces ".trim().replace(/\s+/g, " "));
// find doubled words
console.log("This is is a test the THE end".match(/\b(\w+)\s+\1\b/gi));
// extract numbers, including negatives and decimals
console.log("Temp -3.5C to 12C, delta 15.5".match(/-?\d+(?:\.\d+)?/g).map(Number));
// split camelCase / PascalCase into words
console.log("parseHTTPResponseCode".split(/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/));
// remove a trailing slash (but keep "/" itself)
console.log(["/a/b/", "/a", "/"].map((p) => p.replace(/(?<=.)\/$/, "")));
// mask all but the last 4 digits
console.log("4111 1111 1111 1234".replace(/\d(?=(?:\D*\d){4})/g, "•"));
too many spaces
[ 'is is', 'the THE' ]
[ -3.5, 12, 15.5 ]
[ 'parse', 'HTTP', 'Response', 'Code' ]
[ '/a/b', '/a', '/' ]
•••• •••• •••• 1234
Parsing simple structured lines
const line = "2026-11-18T09:15:02Z WARN [auth] Too many attempts user=ana ip=10.0.0.7";
const logPattern = /^(?<time>\S+) (?<level>[A-Z]+) \[(?<module>[\w-]+)\] (?<message>.*?)(?<fields>(?: \w+=\S+)*)$/;
const { time, level, module, message, fields } = line.match(logPattern).groups;
const extra = Object.fromEntries(Array.from(fields.matchAll(/(\w+)=(\S+)/g), ([, k, v]) => [k, v]));
console.log({ time, level, module, message, extra });
{
time: '2026-11-18T09:15:02Z',
level: 'WARN',
module: 'auth',
message: 'Too many attempts',
extra: { user: 'ana', ip: '10.0.0.7' }
}
When not to use a regex
Regexes are great for regular patterns: tokens, simple formats, search and replace. They're the wrong tool for:
- Nested structures like HTML, XML, JSON or nested parentheses. Use
DOMParser,JSON.parseor a real parser. - Full validation of emails and URLs. The real email grammar is enormous, and "valid syntax" doesn't mean the address exists. A light check plus a confirmation email is the practical approach:
const looksLikeEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(["ana@example.com", "ana@localhost", "a b@c.de"].map((e) => looksLikeEmail.test(e)));
console.log(URL.canParse("https://example.com/a?b=1"), URL.canParse("example.com"));
console.log(new URL("https://example.com:8080/path?q=js").port);
[ true, false, false ]
true false
8080
- URLs: use the
URLclass (article 88), which parses exactly the way browsers do. - Dates: use
Date,Intlor Temporal (articles 83 to 85). - Numbers with locale formatting: use
Intl.NumberFormat. - Simple fixed text:
includes,startsWith,splitandreplaceAllwith strings are clearer and faster.
Catastrophic backtracking and ReDoS
JavaScript's regex engine is a backtracking engine: when part of a pattern fails, it goes back and tries other ways of dividing the input among the quantifiers. Normally that's quick. But some patterns give the engine an exponential number of ways to try, and on a string that almost matches, it tries them all:
/^(a+)+$/.test("a".repeat(30) + "!"); // can take seconds or longer
(a+)+ means "one or more groups of one or more a's". A run of 30 a's can be split into groups in about 2²⁹ ways, and when the final ! makes the match fail, the engine tries every split before giving up:
![]()
Each additional character roughly doubles the time. Because regexes run on the main thread, one such pattern can freeze a page, and on a server, an attacker can send crafted input to tie up the CPU. This is called ReDoS (regular expression denial of service), and it has caused real outages.
Warning signs:
- Nested quantifiers:
(a+)+,(\w*)*,(\d+\s?)+. - Overlapping alternatives under a quantifier:
(a|a)+,(\w|\d)+,(.*,)*. - Several adjacent quantified parts that can match the same text:
\s*\s*,.*.*=.
Fixes:
- Remove the nesting:
/^(a+)+$/means the same as/^a+$/, which is linear. - Make alternatives mutually exclusive and prefer specific classes (
[^,]*instead of.*). - Limit input length before matching untrusted text.
- Anchor patterns, so the engine doesn't retry at every starting position.
- Lint for it (eslint-plugin-regexp,
safe-regex-style checks), and for server-side matching of untrusted input consider a linear-time engine such as RE2 (available for Node).
const start = Date.now();
console.log(/^a+$/.test("a".repeat(100_000) + "!"), Date.now() - start < 100);
false true
Keeping regexes maintainable
- Prefer named groups to
$3andm[4]. - Build complex patterns from named pieces:
const part = {
date: String.raw`(?<date>\d{4}-\d{2}-\d{2})`,
amount: String.raw`(?<amount>-?\d+(?:\.\d{2})?)`,
memo: String.raw`(?<memo>.+)`,
};
const entry = new RegExp(`^${part.date},${part.amount},${part.memo}$`);
console.log("2026-11-18,-42.50,Groceries".match(entry).groups);
[Object: null prototype] {
date: '2026-11-18',
amount: '-42.50',
memo: 'Groceries'
}
String.raw keeps backslashes as written (article 16), so you don't have to double them.
- Test each pattern against inputs that should match and inputs that shouldn't, including empty strings, very long strings and non-ASCII text.
- Add a comment with an example of what the pattern matches.
Common questions
Is RegExp.escape available everywhere?
It's part of ES2025 and supported in current browsers and Node.js 24 and later. For older targets, use the one-line replacement shown above or a polyfill.
What's the best regex for validating email addresses?
There isn't a good complete one. Use a light check (something, @, something, dot, something), <input type="email"> in forms, and verify by sending a confirmation email.
How can I tell whether my regex is vulnerable to ReDoS?
Look for nested or overlapping quantifiers, then test with a long almost-matching input (a long run of the repeated character plus one character that makes the match fail). If the time grows sharply with the length, rewrite the pattern. Linters for regexes can flag many of these patterns automatically.
Can a regex match balanced parentheses?
Not in JavaScript: its regexes have no recursion, so they can't count arbitrary nesting. Use a loop with a counter or a parser.
Summary
- Always escape user input with
RegExp.escape(or the classic replace) before putting it in a pattern; use plain string methods when you don't need patterns. - ES2025 adds inline modifiers
(?i:...)and duplicate named groups across alternatives. - Normalize Unicode text (
normalize("NFC")orNFKDplus\p{M}removal) before matching. - Regexes suit regular formats; use parsers for HTML/JSON,
URLfor URLs,Intland date APIs for dates and numbers. - Nested or overlapping quantifiers can backtrack exponentially (ReDoS); remove nesting, make alternatives exclusive, limit input length.
- Keep patterns readable with named groups,
String.rawcomposition, comments and tests.
Practice Questions
Why is new RegExp(userInput, "g") dangerous, and what's the fix?
Answer
Special characters in the input become regex syntax: . matches anything, ( can throw a SyntaxError, and crafted input could even create a slow pattern. Use new RegExp(RegExp.escape(userInput), "g").
Rewrite /^(\d+)*$/ so it can't backtrack catastrophically.
Answer
/^\d*$/. The nested quantifier adds nothing but exponentially many ways to split the digits.
Write a pattern that matches "Error" case-insensitively but requires ":" and a digit code after it, like "ERROR: 42".
Answer
/^(?i:error): \d+$/, or /^[Ee][Rr][Rr][Oo][Rr]: \d+$/ where inline modifiers aren't supported.
Why does /résumé/.test(input) sometimes fail even when the text looks identical?
Answer
The input may use decomposed characters (e plus a combining accent) while the pattern uses precomposed ones. Normalize the input with input.normalize("NFC") first.
Previous: JavaScript Regex Flags and Methods: test, exec, match, matchAll, replace, split and lastIndex
Next: JavaScript Dates: the Date Object, Timestamps, Time Zones, Date Arithmetic and Formatting

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.