Regular Expressions
Regular Expressions
Section titled βRegular ExpressionsβWhat it means
Section titled βWhat it meansβA regular expression (regex) is a pattern used to match, extract, or replace text. JavaScript represents them as RegExp objects, either via a literal (/pattern/flags) or the RegExp constructor (useful when the pattern is built dynamically from a string). Common flags: g (global β find all matches, not just the first), i (case-insensitive).
Examples
Section titled βExamplesβconst pattern = /\d+/; // matches one or more digitsconsole.log(pattern.test("abc123")); // true
const match = "abc123def456".match(/\d+/g); // global flag -- find all matchesconsole.log(match); // ["123", "456"]
const email = /^[\w.-]+@[\w.-]+\.\w+$/;console.log(email.test("alice@example.com")); // true
const cleaned = "Hello World".replace(/\s+/g, " "); // collapse whitespaceconsole.log(cleaned); // "Hello World"
// Capture groupsconst dateMatch = "2026-06-15".match(/(\d{4})-(\d{2})-(\d{2})/);console.log(dateMatch[1], dateMatch[2], dateMatch[3]); // 2026 06 15Common mistake
Section titled βCommon mistakeβForgetting the g flag when you need all matches, not just the first one β .match() without g returns only the first match (plus capture-group details); with g it returns every match but drops capture-group info.
const text = "cat, bat, hat";
console.log(text.match(/\w+at/)); // only the first match: ["cat", ...]console.log(text.match(/\w+at/g)); // all matches: ["cat", "bat", "hat"]Quick practice
Section titled βQuick practiceβ-
What does the
gflag do on a regex?Answer
Makes the match "global" β instead of stopping at the first match, methods like.match()and.replace()find/act on every match in the string. -
Whatβs the difference between
.test()and.match()?Answer
.test()(called on the regex) returns a boolean β whether the pattern matches;.match()(called on the string) returns the actual matched text (ornullif there's no match). -
How do you extract just the year from
"2026-06-15"using a regex capture group?Answer
"2026-06-15".match(/(\d{4})-\d{2}-\d{2}/)[1]β the parenthesized group captures"2026", accessible at index1of the match result.