Cheat sheetJavaScript
Regex
Patterns, groups, flags, and practical examples for validation and parsing.
Flags
| g | Global — find all matches |
|---|---|
| i | Case-insensitive |
| m | ^/$ match line boundaries |
| s | . matches newlines |
| u | Unicode mode |
| y | Sticky — from lastIndex |
Atoms
javascript
/./ // any char (except newline unless s)
/\d/ // digit [0-9]
/\w/ // word [A-Za-z0-9_]
/\s/ // whitespace
/[aeiou]/ // class
/[^0-9]/ // negated
/^hi/ // start
/end$/ // end
/a|b/ // alternationQuantifiers
javascript
/a*/ // 0+
/a+/ // 1+
/a?/ // 0–1
/a{2}/ // exactly 2
/a{2,}/ // 2+
/a{2,4}/ // 2–4
/a+?/ // lazy (non-greedy)Groups & methods
javascript
const re = /(?<year>\d{4})-(\d{2})-(\d{2})/;
const m = '2026-08-06'.match(re);
// m[0] full, m[1] year (or m.groups.year), m[2] month
're'.test(s)
s.match(re)
s.matchAll(/\w+/g)
s.replace(/\s+/g, ' ')
s.split(/,\s*/)Practical patterns
javascript
// Simple email-ish (not RFC-complete)
const email = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// Trim trailing slashes
path.replace(/\/+$/, '')
// Capture slug
const slug = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;Interview tips
- ✓Say when regex is wrong (HTML parsing, complex grammars).
- ✓Prefer named groups for readability.
- ✓Know catastrophic backtracking exists on hostile input.
Common mistakes
- !Forgetting g flag and wondering why replace only hits once.
- !Using match with g — loses capture groups; use matchAll.
- !Anchoring mistakes (^/$) on multi-line input without m.