Skip to content

Regular Expressions

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).

const pattern = /\d+/; // matches one or more digits
console.log(pattern.test("abc123")); // true
const match = "abc123def456".match(/\d+/g); // global flag -- find all matches
console.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 whitespace
console.log(cleaned); // "Hello World"
// Capture groups
const dateMatch = "2026-06-15".match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(dateMatch[1], dateMatch[2], dateMatch[3]); // 2026 06 15

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"]
  1. What does the g flag do on a regex?

    AnswerMakes the match "global" β€” instead of stopping at the first match, methods like .match() and .replace() find/act on every match in the string.
  2. 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 (or null if there's no match).
  3. 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 index 1 of the match result.