|$ 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

JavaScriptIntermediate
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)
2const email = /^[\w.-]+@[\w.-]+\.\w{2,}$/;
3
4// Constructor syntax (runtime, dynamic patterns)
5const flag = "i";
6const 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
1const str = "Hello 123 World 456";
2const pattern = /\d+/g;
3
4// RegExp methods
5pattern.test(str); // true — matches at least once
6pattern.exec(str); // ["123", index: 6, ...] — next match with groups
7
8// String methods
9str.match(pattern); // ["123", "456"] — all matches (global)
10str.matchAll(pattern); // Iterator of match objects (ES2020)
11str.search(/World/); // 11 — index of first match (-1 if none)
12str.replace(/\d+/g, "X"); // "Hello X World X"
13str.replaceAll(/\d+/g, "X"); // "Hello X World X" (ES2021)
14str.split(/\s+/); // ["Hello", "123", "World", "456"]
Capturing Groups

Capture parts of a match using parentheses, including named groups for readability.

regex-groups.js
JavaScript
1const date = "2024-01-15";
2
3// Numbered groups
4const numMatch = date.match(/(\d{4})-(\d{2})-(\d{2})/);
5numMatch[1]; // "2024" (first group)
6numMatch[2]; // "01" (second group)
7
8// Named groups (ES2018)
9const named = date.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
10named.groups.year; // "2024"
11named.groups.month; // "01"
12named.groups.day; // "15"
13
14// Non-capturing group
15const 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.