Regular expressions
Patterns, flags, character classes, groups, named captures and replace/matchAll.
A regular expression (regex) is a pattern that describes text: "a word starting with a capital letter", "six digits", "anything that looks like an email". They're a compact mini-language built into JavaScript for searching, validating, extracting and replacing text. They look cryptic at first, but a small set of building blocks covers most real-world needs.
Creating a regex#
Use the constructor when the pattern comes from a variable. If that variable holds user input, escape it first so characters like . or ? are treated literally — modern engines have RegExp.escape(str) for this (Node 24+, current browsers).
The core methods#
Building blocks#
Characters and classes
Quantifiers: how many?
Anchors and boundaries
For validation, always anchor with
^...$. Without them,/\d{6}/happily matches"abc1234567xyz".
Alternation
Flags#
Groups and captures#
Parentheses group parts of a pattern and capture what they matched:
Named groups
Names make complex patterns readable:
Non-capturing groups
(?:...) groups without capturing — useful with quantifiers or alternation:
Replacing with groups
Iterating all matches with matchAll#
matchAll requires the g flag and gives you full details (groups, index) for every match.
Greedy vs lazy#
Quantifiers are greedy: they match as much as possible. Add ? to make them lazy:
Don't parse real HTML with regex — use the DOM (
DOMParser) instead. Small, predictable snippets like this are fine.
Lookahead and lookbehind#
Check what comes before or after without including it in the match:
Practical patterns#
A robust slugify
The lastIndex trap#
A regex with g or y remembers where it stopped in lastIndex, so reusing it with test can give alternating results:
Don't use the g flag with test(), or create the regex fresh each time.
Tips#
- Build and debug patterns on a site like regex101.com (choose the JavaScript flavour) — it explains each part.
- Prefer readable code over clever regex. Two simple checks beat one unreadable pattern.
- Email and URL validation via regex is always approximate. For URLs,
URL.canParse(str)ornew URL(str)is better; for email, usetype="email"plus a confirmation email. - Beware of patterns with nested quantifiers like
(a+)+on user input — they can take exponential time ("ReDoS").
Common mistakes#
- Forgetting to escape
.—/1.5/matches"105". - Forgetting anchors in validation patterns.
- Expecting
replacewith a string pattern or a regex withoutgto replace everything. - Using
matchwithgand expecting groups — usematchAll.
What's next#
Next, handle dates and times correctly and format numbers, currencies and dates for any locale with Intl.
Check your understanding
Quick quiz
1.What does the
gflag do in/cat/g?2.Which string does
/^\d{3}-\d{4}$/match?3.In
"2026-09-30".replace(/(\d+)-(\d+)-(\d+)/, "$3/$2/$1"), what is the result?
Finished reading?
Mark this lesson complete to track your progress.