Regex Cheat Sheet for JavaScript

A compact reference for JavaScript regular expressions: character classes, quantifiers, anchors, groups, lookarounds and flags, with examples you can test live.

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.

Regex TesterWrite a pattern and see every match highlighted as you type, with capture groups and positions. Matching runs in a background thread, so even a catastrophically backtracking pattern will not freeze the page.

Characters and classes

PatternMatches
.Any character except a line break
\dA digit, 0 to 9
\wA letter, digit or underscore
\sWhitespace: space, tab, line break
\D \W \SThe opposite of \d, \w, \s
[abc]One of a, b or c
[a-z]One character in the range
[^abc]Any character except a, b, c
\.A literal dot; escape . * + ? ^ $ ( ) [ ] { } \ to match them literally

Quantifiers

PatternMeaning
*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

PatternMatches
^Start of the input, or of a line with the m flag
$End of the input, or of a line with the m flag
\bA word boundary
\BAnywhere that is not a word boundary

Groups and alternatives

PatternMeaning
(abc)Capturing group, numbered from 1
(?<year>\d{4})Named capturing group
(?:abc)Non-capturing group
a|bEither a or b
\1Back-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.

PatternMeaning
a(?=b)a followed by b
a(?!b)a not followed by b
(?<=b)aa preceded by b
(?<!b)aa not preceded by b

Flags

FlagEffect
gFind every match, not just the first
iIgnore case
m^ and $ match at each line
s. also matches line breaks
uFull Unicode support, including \p{...} classes
ySticky: 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.

Try the tool