Regex

Regex Cheat Sheet with Examples (JavaScript)

By Laxmi SolutionsPublished 2 min read

Regular expressions describe patterns in text: an email address, a date, a log line. The syntax is dense but small. This cheat sheet covers the parts you'll use every week, in JavaScript's flavour, with examples to paste into a regex tester.

Characters and classes

Matching single characters
PatternMatches
.Any character except a newline (any character with the s flag)
\d / \DA digit / anything but a digit
\w / \WA word character (letter, digit, underscore) / anything else
\s / \SWhitespace (space, tab, newline) / anything else
[abc]One of a, b or c
[^abc]Any character except a, b or c
[a-z0-9]A character in either range
\.A literal dot; escape any of . * + ? ( ) [ ] { } ^ $ | \

Anchors and quantifiers

Position and repetition
PatternMeaning
^ / $Start / end of the text (of each line with the m flag)
\bA word boundary
* / + / ?0 or more / 1 or more / 0 or 1
{3} / {2,} / {2,5}Exactly 3 / at least 2 / between 2 and 5
*? / +?Lazy: match as few as possible

Quantifiers are greedy by default. On <b>bold</b>, the pattern <.+> matches the whole string, while the lazy <.+?> matches just <b>.

Groups, alternation and lookarounds

Grouping
PatternMeaning
(abc)Capture group, numbered from 1
(?<year>\d{4})Named capture group
(?:abc)Group without capturing
cat|dogEither alternative
\1Back-reference to group 1
(?=x) / (?!x)Followed by x / not followed by x
(?<=x) / (?<!x)Preceded by x / not preceded by x

Flags

JavaScript regex flags
FlagEffect
gGlobal: find all matches, not just the first
iCase-insensitive
mMultiline: ^ and $ match at line breaks
sDot-all: . also matches newlines
dIndices: report where each group starts and ends
uUnicode: treat the pattern and text as Unicode code points

Patterns you'll actually use

ISO date (2026-10-23)        ^(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})$
Simple email check           ^[^\s@]+@[^\s@]+\.[^\s@]+$
Hex colour (#fff, #1e1e1e)   ^#(?:[0-9a-fA-F]{3}){1,2}$
Trailing whitespace          [ \t]+$                (flags: gm)
Duplicate word ("the the")   \b(\w+)\s+\1\b        (flags: gi)
Number with commas           ^\d{1,3}(?:,\d{3})*$

Validate formats like email loosely with a regex, then confirm the real thing another way (send a confirmation email). A pattern that tries to cover every valid address is unreadable and still wrong.

Avoid catastrophic backtracking

Nested quantifiers such as (a+)+$ or (\w+\s?)*$ can take exponentially long on text that almost matches: a short input can freeze a page or a server. Keep each part of a pattern unambiguous, avoid a quantifier directly around another, and anchor patterns when you can.

The regex playground in Code Editor runs each pattern in a background worker with a time limit, so a runaway pattern stops with a timeout instead of freezing your tab. Matches and named groups update as you type, and you can toggle each flag above.