JavaScript Regex

Pattern Match Text — Search, Validate, Replace

JavaScript Regex

Regular expressions are tiny pattern languages for text. JavaScript has them as a first-class type — `/pattern/flags`.

6 min read Level 3/5 #regex#RegExp#patterns
What you'll learn
  • Read regex literals and flags
  • Use `.test`, `.match`, `.matchAll`, `.replace`
  • Capture groups and reference them in replacements

A regular expression is a pattern that matches text. In JavaScript you write them between slashes, like /cat/. Flags after the closing slash change behavior — /cat/i matches case-insensitively.

A Few Patterns to Get Started

PatternMatches
catThe literal text “cat”
c.t”cat”, “cot”, “c@t” — . is any single character
\dAny digit (0–9); \D is the inverse
\wWord char (letter, digit, _); \W is the inverse
\sWhitespace; \S is non-whitespace
[abc]Any one of a, b, c
[a-z]Any lowercase letter
[^abc]Anything EXCEPT a, b, c
a*Zero or more a
a+One or more a
a?Zero or one a
a{2,4}Two to four a
^, $Start / end of string (or line with m flag)
(abc)Capture group
`ab`

The Methods You’ll Use Most

.test() — boolean match script.js
const isDigits = /^\d+$/;

console.log(isDigits.test("123"));  // true
console.log(isDigits.test("12a"));  // false
console.log(isDigits.test(""));     // false (needs at least one)
▶ Preview: console
.match() — first match + groups script.js
const re = /(\w+)@(\w+)/;
const m = "ada@example".match(re);

console.log(m[0]);     // "ada@example"  (the whole match)
console.log(m[1]);     // "ada"          (group 1)
console.log(m[2]);     // "example"      (group 2)
▶ Preview: console
.matchAll() — every match with groups script.js
const re = /(\w+)@(\w+)/g;        // g flag required for matchAll
const matches = "a@b c@d".matchAll(re);

for (const m of matches) {
  console.log(m[1], "->", m[2]);
}
// "a -> b"
// "c -> d"
▶ Preview: console
.replace() — with backreferences script.js
// Swap "first last" → "last, first"
const fixed = "Ada Lovelace".replace(/(\w+) (\w+)/, "$2, $1");
console.log(fixed);   // "Lovelace, Ada"
▶ Preview: console

$1, $2, … refer to capture groups in the replacement string. For more complex replacements, pass a function:

.replace() — with a function script.js
const out = "abc 12 xyz 7".replace(/\d+/g, n => Number(n) * 2);
console.log(out);   // "abc 24 xyz 14"
▶ Preview: console

Flags Cheat Sheet

FlagMeaning
gGlobal — find all matches, not just the first
iCase-insensitive
mMultiline — ^ and $ match line starts/ends
sDot-all — . matches newlines too
uUnicode — proper handling of non-BMP characters
ySticky — match must start at lastIndex

Named Groups

For readability, name captures with (?<name>...).

Named capture groups script.js
const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const m = "2026-05-11".match(re);

console.log(m.groups.year);   // "2026"
console.log(m.groups.month);  // "05"
▶ Preview: console

Building From a String

You can also build a regex at runtime with the RegExp constructor — useful when the pattern comes from user input.

Dynamic pattern script.js
const term = "cat";
const re = new RegExp(`\\b${term}\\b`, "i");

console.log(re.test("The cat sat."));   // true
console.log(re.test("catalog"));         // false  (word boundary)
▶ Preview: console

Common Patterns

// Trim trailing whitespace from each line
text.replace(/[ \t]+$/gm, "");

// Collapse multiple spaces
text.replace(/\s+/g, " ");

// Naive email check (not RFC-perfect; just a sanity test)
/^\S+@\S+\.\S+$/.test(email);

// Match the part after the last "/"
url.match(/[^/]+$/)?.[0];

Up Next

Another data type with surprising sharp edges — dates.

JavaScript Dates →