JavaScript Regex Replacement and matchAll()
Quick answer
Regex-aware string methods can search, extract multiple matches and construct replacements using captured fields.
How it works
match returns match information without g and whole matched substrings with g; matchAll returns an iterator of match results with captures and requires g for ordinary regex arguments. search returns the first index or -1. replace with a global regex replaces each match; callbacks receive the match, captures, offset, source and optional named groups. replaceAll requires a global regex.
const text = "x=2 y=5";console.log(text.replace(/\d+/g, n => String(Number(n) * 2)));Expected output in Node.js:
x=4 y=10Each numeric match is converted, doubled and returned as text.
const matches = [..."A12 B34".matchAll(/([A-Z])(\d+)/g)];console.log(matches.map(m => m[2]).join(","));Expected output in Node.js:
12,34Each iterator result includes the numeric capture at index 2.
Common mistakes
Global match does not retain numbered capture results in its returned array. Use matchAll when each match needs its captures.
Practice
Extract label-value pairs from a short text and transform each numeric value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Regex Replacement and matchAll() — Knowledge Check
Apply the taught concept and predict the output.
Which method iterates global regex matches while preserving capture groups?
What is the return value of search when no regex match exists?
What must an ordinary regex argument to matchAll include?
What is the exact console output in JavaScript Regex Replacement and matchAll() example 1?
const text = "x=2 y=5";console.log(text.replace(/\d+/g, n => String(Number(n) * 2)));What is the exact console output in JavaScript Regex Replacement and matchAll() example 2?
const matches = [..."A12 B34".matchAll(/([A-Z])(\d+)/g)];console.log(matches.map(m => m[2]).join(","));