Skip to content

Lesson 14 of 50JavaScript in depth

Regular Expressions

Read and write JavaScript regex with confidence: groups, flags, matchAll and replace callbacks, Unicode, the lastIndex trap, and how to avoid ReDoS.

17 min read0/5 questions

A support engineer pastes you 5,000 lines of server logs and asks which customers hit a PAYMENT_FAILED error, with their order ids, in a spreadsheet. A product manager wants every DD/MM/YYYY date in an import file turned into ISO format. A search box needs to highlight what the user typed, even when they type c++. Each of these is a few lines with a regular expression (regex), a small pattern language for finding and reshaping text, and an afternoon of fiddly loops without one. Regex also has a dark side: in July 2019, a single badly written pattern took down a large part of Cloudflare's network for about half an hour by eating all the CPU. This lesson teaches you to read and write patterns, use the JavaScript APIs correctly, and recognise the patterns that can hurt you.

Two ways to make a regex

Most patterns are written as literals between slashes, with flags after the closing slash. When the pattern is only known at runtime, you build it with the RegExp constructor from a string.

const literal = /\d{3}-\d{4}/g;
const built = new RegExp("\\d{3}-\\d{4}", "g"); // same pattern

Notice the doubled backslashes. In a string, "\d" is just d, because the string escape eats the backslash before RegExp ever sees it. You need "\\d" so the string contains a real backslash. This is the most common reason a constructed regex "does not match anything".

The bigger danger is putting user input into a pattern. If someone searches for c++ and you write new RegExp(query), the + signs are quantifiers, and new RegExp("c++") throws a SyntaxError. Worse, a malicious pattern can freeze your server (see the last section). Always escape input first. ES2025 added RegExp.escape, available in current browsers and Node 24. For older runtimes, the classic helper escapes every special character:

JavaScript
const escape = RegExp.escape ?? ((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); const query = "c++ (beta)";const re = new RegExp(escape(query), "gi");console.log(re.source.includes("\\+"));console.log("Learn C++ (Beta) today".replace(re, (m) => `[${m}]`));
Output
Press Run (⌘ Enter) to see what happens.

$& in a replacement string means "the whole match", so the helper puts a backslash in front of each special character it finds.

The building blocks

A pattern is a sequence of pieces, each matching some text. You only need a short list to read most real-world regex.

PieceMatches
abcThose characters, in order
.Any one character except a line break (unless the s flag)
[aeiou], [a-z0-9]One character from the set or range
[^0-9]One character not in the set
\d, \w, \sA digit, a word character ([A-Za-z0-9_]), whitespace
\D, \W, \SThe opposites
*, +, ?Zero or more, one or more, zero or one of the previous piece
{3}, {2,4}, {2,}Exactly 3, 2 to 4, 2 or more
^, $Start and end of the input (of each line with the m flag)
\bA word boundary: between a \w and a non-\w character
a|bEither side

Special characters (. * + ? ^ $ { } ( ) | [ ] \ /) need a backslash to match literally: \. matches a dot. Inside a character class most of them lose their meaning, so [.] also matches a dot.

Anchors are what turn "contains" into "is". /\d{4}/.test("abc12345") is true, because four digits appear somewhere. /^\d{4}$/ only accepts a string that is exactly four digits. Forgetting anchors is the number one validation bug in code review. Watch alternation too: /^yes|no$/ means ^yes or no$, so it matches "yesterday". Group it: /^(?:yes|no)$/.

Greedy versus lazy

Quantifiers are greedy: they grab as much as they can, then give characters back only if the rest of the pattern fails. Adding ? after a quantifier (*?, +?, ??) makes it lazy: as little as possible, growing only when needed.

JavaScript
const html = '<b>bold</b> and <i>italic</i>';console.log(html.match(/<.+>/)[0]); // greedy: runs to the last >console.log(html.match(/<.+?>/g)); // lazy: stops at the first >console.log(html.match(/<[^>]+>/g)); // usually better: "anything but >"
Output
Press Run (⌘ Enter) to see what happens.

The third pattern is often the best fix. A negated class like [^>]+ cannot overshoot, says exactly what you mean, and avoids backtracking entirely.

Quick check
What does "a1b22c333".match(/\d+?/g) return?
Need a nudge? A hint rules out a wrong answer.

Groups, backreferences and lookaround

Parentheses do two jobs: they group pieces so a quantifier or | applies to all of them, and they capture what they matched so you can use it later.

  • (\d{4}) is a capturing group, numbered from 1 by its opening parenthesis.
  • (?<year>\d{4}) is a named group. Use names: match.groups.year survives someone adding a group earlier in the pattern, while match[1] silently shifts.
  • (?:...) groups without capturing. Use it when you only need grouping.
  • \1 or \k<year> is a backreference: "the same text that group matched". /(\w)\1/ finds doubled letters.

Lookaround checks what is next to the current position without consuming it. (?=...) is a lookahead, (?!...) a negative lookahead, (?<=...) a lookbehind and (?<!...) a negative lookbehind. They are how you say "a number followed by EUR, but give me only the number".

JavaScript
// Reformat DD/MM/YYYY as YYYY-MM-DD using named groups in the replacementconst text = "Joined 03/11/2025, renewed 15/01/2026.";const dmy = /\b(?<day>\d{2})\/(?<month>\d{2})\/(?<year>\d{4})\b/g;console.log(text.replace(dmy, "$<year>-$<month>-$<day>")); // Lookahead and lookbehindconsole.log("30 EUR, 45 USD, 12 EUR".match(/\d+(?= EUR)/g));console.log("$30, £45, $12".match(/(?<=\$)\d+/g)); // Backreference: doubled words, a common typoconsole.log("it was the the best".match(/\b(\w+) \1\b/)[0]);
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputJavaScript

What does this print?

const m = "SKU-2026-blue".match(/(?<code>[A-Z]+)-(\d+)-(?:red|blue)/);
console.log(m.length, m.groups.code, m[2]);
Need a nudge? Hints walk you through it.

Flags

Flags change how the whole pattern behaves. You will see all of these in real code.

FlagNameEffect
gglobalFind every match, not just the first. Makes the regex stateful (see below)
iignore casea matches A
mmultiline^ and $ match at each line, not just the ends of the input
sdotAll. also matches line breaks
uunicodeTreats the pattern and input as code points; enables \p{...}; stricter syntax
vunicodeSetsEverything u does, plus set operations and multi-character properties (ES2024)
ystickyMatch only at exactly lastIndex. Used in tokenizers
dindicesAdds match.indices with start and end positions of each group

The d flag is underused. If you are building a highlighter or an editor feature, match.indices.groups.year gives you [start, end] for that group directly, so you do not have to search for the text again.

The JavaScript API

Regex methods are split between strings and regex objects, which confuses everyone at first.

  • re.test(str) returns true or false. Use it for yes or no checks.
  • str.match(re) without g returns the first match with its groups and index, or null. With g it returns only an array of matched strings, and every group is lost.
  • str.matchAll(re) requires the g flag and returns an iterator of full match objects, groups included. This is what you want for "every match, with details". As you saw in Iterators and Generators, iterators are one-shot, so spread it with [...str.matchAll(re)] if you need it twice.
  • str.replace(re, replacement) and str.replaceAll(re, replacement) accept a string with $1, $<name> and $&, or a function that receives the match and its groups and returns the replacement. replaceAll throws if the regex lacks g, which is a helpful guard.
  • str.split(re) splits on a pattern: "a, b;c".split(/[,;]\s*/).
JavaScript
const log = `2026-10-21 ERROR PAYMENT_FAILED order=A-1001 user=ada2026-10-21 INFO LOGIN user=sam2026-10-22 ERROR PAYMENT_FAILED order=A-1044 user=lin`; const re = /^(?<date>\S+) ERROR PAYMENT_FAILED order=(?<order>\S+) user=(?<user>\w+)$/gm;const rows = [...log.matchAll(re)].map((m) => m.groups);console.table(rows); // A replace callback can compute anythingconst masked = log.replace(/user=(\w+)/g, (_, name) => `user=${name[0]}***`);console.log(masked.split("\n")[1]);
Output
Press Run (⌘ Enter) to see what happens.

The lastIndex trap

A regex with g or y is stateful. It stores lastIndex, the position where the next search starts. exec and test read and update it. After a successful match, lastIndex moves past the match. After a failure, it resets to 0. So reusing one global regex for test across different strings gives answers that alternate for no visible reason.

Predict the outputJavaScript

What does this print?

const isId = /^[A-Z]-\d+$/g;
const ids = ["A-1", "B-2", "C-3"];
console.log(ids.map((s) => isId.test(s)).join(" "));
Need a nudge? Hints walk you through it.

This bug is nasty in production because it depends on the order of inputs. It shows up in validators stored as module-level constants and in filters like items.filter((x) => re.test(x)). The rule is simple: no g on a regex used with test, or create the regex inside the function. matchAll, replace and replaceAll handle lastIndex for you, so they are safe.

Unicode: why u and v matter

Without the u flag, a regex sees text as UTF-16 code units, the same chunks the Strings and templates lesson warned about. Most emoji take two code units, so . matches half an emoji and /^.$/ fails on "\u{1F600}" (a smiling face). With u, the regex works on whole code points, and you gain Unicode property escapes: \p{L} (any letter in any script), \p{Lu} (uppercase letter), \p{N} (number), \p{Script=Greek}, and \P{...} for the opposite.

That matters for names. \w is ASCII only, even with the u flag, so /^\w+$/ rejects José, Zoë and every name in Arabic or Chinese. A "letters, spaces, apostrophes and hyphens" rule is /^[\p{L}\p{M}' -]+$/u, where \p{M} allows combining accent marks.

The v flag (ES2024, in all current browsers) is a stricter, upgraded u. It adds set operations inside classes, written -- for difference and && for intersection, and properties that match multi-code-point sequences, such as \p{RGI_Emoji} for a whole emoji, including skin tones and flags.

JavaScript
const face = "\u{1F600}"; // one emoji, two UTF-16 code unitsconsole.log(/^.$/.test(face), /^.$/u.test(face));console.log(/^\w+$/u.test("José"), /^[\p{L}\p{M}' -]+$/u.test("José O'Neil")); // v flag: letters that are not plain ASCII a to zconsole.log("naïve café".match(/[\p{L}--[a-z]]/gv));// v flag: whole emoji, even multi-part ones// thumbs up with a skin tone, then the UK flag (two regional indicators)const text = "ok \u{1F44D}\u{1F3FD} go \u{1F1EC}\u{1F1E7}";console.log(text.match(/\p{RGI_Emoji}/gv).length);
Output
Press Run (⌘ Enter) to see what happens.

For new code, prefer v (or u if you must support older runtimes). Both also make the syntax stricter, so a typo such as an unescaped { becomes a SyntaxError instead of being silently treated as a literal.

Catastrophic backtracking (ReDoS)

JavaScript's regex engine is a backtracking engine. When part of a pattern can match the same text in several ways, and a later part fails, the engine goes back and tries every other way before giving up. Usually there are only a few ways. With nested quantifiers like (a+)+, the number of ways to split a run of characters doubles with each extra character.

How /^(a+)+$/ fails on "aaa!"
a
0
a
1
a
2
!
3
groups = (aaa)tries = 1

The inner a+ greedily takes all three as as one group. Then $ meets ! and fails.

1/5

You can measure it. Each extra two characters makes the search roughly four times slower, while the equivalent pattern without nesting stays instant:

JavaScript
for (const n of [18, 20, 22, 24, 26]) { const input = "a".repeat(n) + "!"; const t0 = performance.now(); /^(a+)+$/.test(input); const slow = performance.now() - t0; const t1 = performance.now(); /^a+$/.test(input); const fast = performance.now() - t1; console.log(`n=${n} nested ${slow.toFixed(1)} ms flat ${fast.toFixed(2)} ms`);}
Output
Press Run (⌘ Enter) to see what happens.

This is ReDoS, regular expression denial of service. If an attacker can send input to a vulnerable pattern on your server, one request can block the Node event loop for seconds or minutes, and every other user waits. The Cloudflare outage came from a pattern containing .*(?:.*=.*), where several .* pieces competed for the same characters.

Patterns to be suspicious of:

  • A quantified group containing a quantifier: (a+)+, (\w*)*, (\d+\s?)+.
  • Alternatives that overlap inside a repeat: (a|aa)+, (\w|\d)+.
  • Several adjacent .* or \s* that can trade characters: \s*.*\s*$.

Fixes, from best to fallback: rewrite so each character can be matched only one way (/^a+$/, or a negated class like [^,]* instead of .*), cap the input length before matching, and for patterns you do not control, run them with a linear-time engine such as RE2 (the re2 package in Node). eslint-plugin-regexp flags many of these patterns in review, which is cheap insurance.

Match the pairs0/5 matched

Match each task to the flag or feature it needs.

Choose an item, then its match on the other side.
Quick check
Which pattern is at risk of catastrophic backtracking on a long input that does not match?
Need a nudge? A hint rules out a wrong answer.
Key terms
regular expression
A pattern language for finding, validating and reshaping text.
quantifier
A piece such as *, +, ? or {2,4} that says how many times the previous piece may repeat.
capturing group
Parentheses that remember the text they matched, by number or by name with (?<name>...).
lookaround
A zero-width check, such as (?=...) or (?<=...), on what comes after or before the current position.
lastIndex
The position where a g or y regex starts its next search. Updated by exec and test.
Unicode property escape
A class like \p{L} that matches by Unicode category. Needs the u or v flag.
ReDoS
Denial of service from catastrophic backtracking, where a regex takes exponential time on crafted input.