Regular expression basics
A regex combines literal characters with operators. A dot often matches any character except line terminators, square brackets define a character class, and quantifiers such as *, +, and {2,4} control repetition.
Anchors such as ^ and $ describe positions rather than consuming characters. Escaping matters twice when a pattern is written inside a JavaScript string.
JavaScript regex patterns and flags
g: find all successive matches.i: ignore letter case.m: make line anchors work across multiple lines.s: allow dot to match line terminators.u: enable Unicode-aware parsing and matching behavior.y: require a match at the current lastIndex position.
Choose only flags the workflow needs. The same pattern can produce different results when global, multiline, or Unicode behavior changes.
Capture groups and named groups
const match = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
.exec('Released 2026-08-31');
console.log(match?.groups?.year); // 2026Named groups make extraction code easier to understand. Use (?:...) when grouping is needed for precedence but the substring does not need to be captured.
Practical JavaScript regex examples
Hex color
^#[0-9a-fA-F]{6}$Simple slug
^[a-z0-9]+(?:-[a-z0-9]+)*$These examples describe narrow formats. They are not universal validators for every color notation or URL path. Define the accepted format before writing the pattern.
A reliable regex testing workflow
- Write down examples that must match and must not match.
- Start with the smallest useful pattern.
- Open the Regex Tester and select JavaScript flags.
- Inspect full matches, group values, and zero-length matches.
- Add edge cases for empty input, Unicode, newlines, and long strings.
- Copy the final pattern into its real code context and test again.
Avoid unexpectedly expensive patterns
Nested or overlapping quantifiers can cause a backtracking engine to try many paths. Patterns similar to (a+)+$ may become expensive when a long near-match fails at the end. Prefer clearer boundaries, reduce ambiguity, cap input length, and avoid applying complex patterns to uncontrolled text on a critical request path.
When testing URL-like text, remember that matching and percent encoding are separate concerns.