Before this lesson

Understand capture groups, JavaScript callbacks, strings and arrays.

What you will be able to do

Extract fields with matchAll and perform predictable transformations with replacement callbacks.

Understand the mechanism

matchAll returns an iterator and requires g on its regex argument. Results include captures and indices, unlike the capture-free result array from global match.

String replacements interpret sequences such as $1 and $& specially. A callback’s returned string is used as result text, which is useful for literal user-provided replacement values.

We extract simple key-value pairs and transform date-shaped text from YYYY-MM-DD into DD/MM/YYYY. Reformatting is not calendar validation; a date such as 2026-02-31 still requires a semantic check.

Runnable example

const pairs = [..."a=12 b=7".matchAll(/([a-z])=(\d+)/g)]
  .map(m => [m[1], Number(m[2])]);
console.log(JSON.stringify(pairs));
console.log("2026-09-29".replace(/^(\d{4})-(\d{2})-(\d{2})$/, (_, y, m, d) => d + "/" + m + "/" + y));
const literalReplacement = "$&";
console.log("a.b".replace(/\./g, () => literalReplacement));
console.log("a.b".replace(/\./g, literalReplacement));

Trace and verify

Extraction yields a with 12 and b with 7. The date becomes 29/09/2026. The callback produces a$&b, whereas a string replacement interprets $& as the matched dot and leaves a.b.

Common mistakes and boundaries

Do not interpolate unchecked search text into a regex. For literal text replacement, string-form replaceAll with a callback avoids constructing a regex at all.

Practice challenge

Replace every dot with the literal text $1 and predict the output.

Reference solution and reasoning

Use "a.b.c".replaceAll(".", () => "$1") to produce a$1b$1c, avoiding both regex escaping and replacement-group interpretation.

Further reading