|$ curl https://forge-ai.dev/api/markdown?path=docs/js/regex
$cat docs/javascript-regular-expressions.md
updated Recently·22 min read·published
JavaScript Regular Expressions
◆JavaScript◆Intermediate
Introduction
Regular expressions are patterns used to match character combinations in strings. JavaScript provides the RegExp object and regex literal syntax (/pattern/flags) for powerful text processing — validation, extraction, replacement, and splitting.
Pattern Syntax
Create regex patterns using literals or the RegExp constructor.
regex-syntax.js
JavaScript
| 1 | // Literal syntax (compile-time, preferred) |
| 2 | const email = /^[\w.-]+@[\w.-]+\.\w{2,}$/; |
| 3 | |
| 4 | // Constructor syntax (runtime, dynamic patterns) |
| 5 | const flag = "i"; |
| 6 | const dynamic = new RegExp("hello", flag); |
| 7 | |
| 8 | // Common flags |
| 9 | // g - global (match all, not just first) |
| 10 | // i - case-insensitive |
| 11 | // m - multiline (^/$ match line boundaries) |
| 12 | // s - dotAll (. matches newlines) |
| 13 | // u - unicode mode |
| 14 | // y - sticky (match from lastIndex) |
Key Methods
Regex methods on RegExp and String prototypes.
regex-methods.js
JavaScript
| 1 | const str = "Hello 123 World 456"; |
| 2 | const pattern = /\d+/g; |
| 3 | |
| 4 | // RegExp methods |
| 5 | pattern.test(str); // true — matches at least once |
| 6 | pattern.exec(str); // ["123", index: 6, ...] — next match with groups |
| 7 | |
| 8 | // String methods |
| 9 | str.match(pattern); // ["123", "456"] — all matches (global) |
| 10 | str.matchAll(pattern); // Iterator of match objects (ES2020) |
| 11 | str.search(/World/); // 11 — index of first match (-1 if none) |
| 12 | str.replace(/\d+/g, "X"); // "Hello X World X" |
| 13 | str.replaceAll(/\d+/g, "X"); // "Hello X World X" (ES2021) |
| 14 | str.split(/\s+/); // ["Hello", "123", "World", "456"] |
Capturing Groups
Capture parts of a match using parentheses, including named groups for readability.
regex-groups.js
JavaScript
| 1 | const date = "2024-01-15"; |
| 2 | |
| 3 | // Numbered groups |
| 4 | const numMatch = date.match(/(\d{4})-(\d{2})-(\d{2})/); |
| 5 | numMatch[1]; // "2024" (first group) |
| 6 | numMatch[2]; // "01" (second group) |
| 7 | |
| 8 | // Named groups (ES2018) |
| 9 | const named = date.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/); |
| 10 | named.groups.year; // "2024" |
| 11 | named.groups.month; // "01" |
| 12 | named.groups.day; // "15" |
| 13 | |
| 14 | // Non-capturing group |
| 15 | const result = "abc123".match(/\w+(?:\d+)/); |
| 16 | // Groups array is empty — no captures |
ℹ
info
Named groups make regex patterns self-documenting and resilient to group reordering. Use (?<name>pattern) syntax for critical extraction logic.