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.
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 patternNotice 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:
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.
| Piece | Matches |
|---|---|
abc | Those 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, \s | A digit, a word character ([A-Za-z0-9_]), whitespace |
\D, \W, \S | The 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) |
\b | A word boundary: between a \w and a non-\w character |
a|b | Either 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.
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.
"a1b22c333".match(/\d+?/g) return?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.yearsurvives someone adding a group earlier in the pattern, whilematch[1]silently shifts.(?:...)groups without capturing. Use it when you only need grouping.\1or\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".
Press Run (⌘ Enter) to see what happens.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]);
Flags
Flags change how the whole pattern behaves. You will see all of these in real code.
| Flag | Name | Effect |
|---|---|---|
g | global | Find every match, not just the first. Makes the regex stateful (see below) |
i | ignore case | a matches A |
m | multiline | ^ and $ match at each line, not just the ends of the input |
s | dotAll | . also matches line breaks |
u | unicode | Treats the pattern and input as code points; enables \p{...}; stricter syntax |
v | unicodeSets | Everything u does, plus set operations and multi-character properties (ES2024) |
y | sticky | Match only at exactly lastIndex. Used in tokenizers |
d | indices | Adds 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)returnstrueorfalse. Use it for yes or no checks.str.match(re)withoutgreturns the first match with its groups andindex, ornull. Withgit returns only an array of matched strings, and every group is lost.str.matchAll(re)requires thegflag 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)andstr.replaceAll(re, replacement)accept a string with$1,$<name>and$&, or a function that receives the match and its groups and returns the replacement.replaceAllthrows if the regex lacksg, which is a helpful guard.str.split(re)splits on a pattern:"a, b;c".split(/[,;]\s*/).
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.
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(" "));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.
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.
The inner a+ greedily takes all three as as one group. Then $ meets ! and fails.
You can measure it. Each extra two characters makes the search roughly four times slower, while the equivalent pattern without nesting stays instant:
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 each task to the flag or feature it needs.
- 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
goryregex starts its next search. Updated byexecandtest. - Unicode property escape
- A class like
\p{L}that matches by Unicode category. Needs theuorvflag. - ReDoS
- Denial of service from catastrophic backtracking, where a regex takes exponential time on crafted input.