ESC

Type to search the knowledge base.

Cheat sheetJavaScript

Regex

Patterns, groups, flags, and practical examples for validation and parsing.

Flags

gGlobal — find all matches
iCase-insensitive
m^/$ match line boundaries
s. matches newlines
uUnicode mode
ySticky — 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/      // alternation

Quantifiers

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.

Related

← All cheat sheets