A compact reference for JavaScript regular expressions: character classes, quantifiers, anchors, groups, lookarounds and flags, with examples you can test live.
· 4 min read
A regular expression describes a pattern of text. This page is a quick reference for the syntax JavaScript supports, with the mistakes that cause most bugs called out. Paste any example into the tester to see what it matches.
A literal dot; escape . * + ? ^ $ ( ) [ ] { } \ to match them literally
Quantifiers
Pattern
Meaning
*
Zero or more
+
One or more
?
Zero or one
{3}
Exactly three
{2,5}
Two to five
{2,}
Two or more
Quantifiers are greedy by default: they take as much as they can. Add ? to make one lazy. Against <a><b>, the pattern <.+> matches the whole string, while <.+?> matches only <a>.
Anchors and boundaries
Pattern
Matches
^
Start of the input, or of a line with the m flag
$
End of the input, or of a line with the m flag
\b
A word boundary
\B
Anywhere that is not a word boundary
Groups and alternatives
Pattern
Meaning
(abc)
Capturing group, numbered from 1
(?<year>\d{4})
Named capturing group
(?:abc)
Non-capturing group
a|b
Either a or b
\1
Back-reference to group 1
Replacement strings refer to groups as $1 or $<year>.
Lookarounds
Lookarounds assert what comes before or after without including it in the match.
Pattern
Meaning
a(?=b)
a followed by b
a(?!b)
a not followed by b
(?<=b)a
a preceded by b
(?<!b)a
a not preceded by b
Flags
Flag
Effect
g
Find every match, not just the first
i
Ignore case
m
^ and $ match at each line
s
. also matches line breaks
u
Full Unicode support, including \p{...} classes
y
Sticky: match only at the current position
Common mistakes
Forgetting to escape the dot.1.5 also matches 1x5; write 1\.5.
Unanchored validation.\d{4} accepts abc12345. Use ^\d{4}$ to require the whole string.
Reusing a global regex. A regex with the g or y flag remembers lastIndex, so calling .test() twice on the same object can give different answers.
Catastrophic backtracking. Nested quantifiers such as (a+)+$ can take exponential time on a failing input. Prefer simpler patterns for untrusted text.