Replacing with patterns and capture groups
A replacement is a search with something to put in place of what was found, and the shape of the search decides how many places change. replace with a text argument replaces the first occurrence and replaceAll replaces every one, while a pattern without the g flag behaves like the first form and a pattern with it like the second.
The replacement text is not a literal: it reads $1 as the first capture group and $<name> as a named one, which is how a date written one way becomes a date written another. The last section passes a function instead of text, so the replacement can be computed from the match. Nothing here writes into the string, so every call returns a new value.
replace and replaceAll with text
With two strings the methods are a plain search and a plain substitution, and the difference is the count. replace changes the first occurrence only, which is what the name does not say, and replaceAll walks the whole string. A program that wants every occurrence and writes replace is the classic bug this pair prevents.
const text = 'a-b-c';
console.log('replace:', text.replace('-', '+'));
console.log('replaceAll:', text.replaceAll('-', '+'));
console.log('unchanged:', text);
console.log('first only:', 'one one one'.replace('one', 'two'));
console.log('every:', 'one one one'.replaceAll('one', 'two'));
node text.js
replace: a+b-c
replaceAll: a+b+c
unchanged: a-b-c
first only: two one one
every: two two two
The first call changed one dash and the second changed both, and the original kept its two dashes because a string never changes. The same pair on words shows the count without the distraction of a separator: one word became two and the other two stayed as they were. A loop over the results of a search is no longer needed for the common case, which is why replaceAll exists at all.
replace with a pattern
A pattern replaces what matches rather than a fixed text, and the g flag decides the count as it did in the previous lesson. replaceAll accepts a string or a global pattern and refuses a pattern without the flag, because it would otherwise replace one occurrence under a name that promises all of them. The program catches that error and prints it.
const text = 'order 42, item 7';
console.log('every digit run:', text.replace(/\d+/g, 'N'));
console.log('first only:', text.replace(/\d+/, 'N'));
console.log('replaceAll with g:', text.replaceAll(/\d+/g, 'N'));
try {
console.log(text.replaceAll(/\d+/, 'N'));
} catch (error) {
console.log(error.name + ': ' + error.message);
}
node pattern.js
every digit run: order N, item N
first only: order N, item 7
replaceAll with g: order N, item N
TypeError: String.prototype.replaceAll called with a non-global RegExp argument
The first call replaced both numbers and the second only the first, and the caught error is the guard that keeps the two names honest. The message names the method and the argument, which is unusually helpful for an error of this kind. A replacement that has to be the same length as the match, such as masking a card number, is a pattern with a g flag and a fixed text.
Capture groups in the replacement
In the replacement text, $1 stands for the first capture group and $2 for the second, so the parts of a match can be reordered. $& is the whole match, $$ is a literal dollar sign and $` and $' are the text before and after the match. The program reorders a date and shows the two references that are easy to forget.
const date = '2024-05-17';
const pattern = /(\d{4})-(\d{2})-(\d{2})/;
console.log('day first:', date.replace(pattern, '$3.$2.$1'));
console.log('no year:', date.replace(pattern, '$2/$1'));
console.log('whole match:', date.replace(/\d{4}/, '[$&]'));
console.log('literal dollar:', date.replace('2024', '$$24'));
console.log('doubled:', 'abc'.replace('b', '$&$&'));
node groups.js
day first: 17.05.2024
no year: 05/2024
whole match: [2024]-05-17
literal dollar: $24-05-17
doubled: abbc
The three groups came back in the order the replacement asked for, and a group that the replacement does not mention is simply dropped. The dollar sign has to be doubled when it is meant literally, because one on its own starts a reference; a replacement built from user input therefore needs that character escaped. The last line is the shortest way to duplicate a match without a capture group.
Named groups and a function
A group can be named with (?<year>...), and the replacement refers to it as $<year>, which survives a change in the order of the groups. When the new text has to be computed, the second argument is a function: it receives the match, the groups in order, the position, the whole string and the named groups, and its return value is the replacement.
const date = '2024-05-17';
const pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
console.log('named:', date.replace(pattern, '$<day>/$<month>/$<year>'));
console.log(
'function:',
date.replace(pattern, (match, year, month, day) => `${day}.${month}.${year}`)
);
console.log(
'groups object:',
date.replace(pattern, (...args) => {
const groups = args[args.length - 1];
return `${groups.day} ${groups.month} ${groups.year}`;
})
);
node named.js
named: 17/05/2024
function: 17.05.2024
groups object: 17 05 2024
The named reference and the function produced two of the same result written two ways, and the third read the same parts from the groups object. A function is the only form that can change a value rather than move it: converting units, masking a secret or applying a lookup all belong there. The arguments before the groups object are positional, so a pattern with many groups is easier to read with names.
Exercises
- Replace every space in 'a b c' with a dash, once with replace and once with replaceAll. How many dashes does each result have?
- Call replaceAll with a pattern that has no flag in pattern.js and read the message. Which two names does it mention?
- Swap the order of the groups in the first replacement of groups.js. Which output line changes, and how?
- Replace the year in the named pattern with $<year> twice in one replacement. What does the result look like?
- Return an empty string from the function in named.js. What happens to the date, and why is that a way to delete a match?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does this program print?
console.log('a-b-c'.replace('-', '+'));Answer
a+b-c
replace with a text argument changes the first occurrence only.
-
What does this program print?
console.log('a-b-c'.replaceAll('-', '+'));Answer
a+b+c
replaceAll changes every occurrence, which is the difference from replace.
-
What does
'2024-05-17'.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3.$2.$1')return?Answer
17.05.2024
The references stand for the groups in the order the replacement writes them.
-
What does
$&stand for in a replacement?Answer
The whole match
The reference repeats the matched text, and $1 is the first group.
-
How is a literal dollar sign written in a replacement?
Answer
$$
One dollar sign starts a reference, and doubling it writes the character itself.
-
What does
replaceAlldo with a pattern that has nogflag?Answer
It throws a TypeError
The method refuses a non-global pattern instead of quietly replacing one match.
-
What does a replacement function receive as its first argument?
Answer
The matched text
The match comes first, then the groups, then the position and the string.
-
Why are named groups easier than numbered ones?
Answer
The reference names the part instead of counting it
A name survives a change in the order of the groups, and the numbered reference does not.
-
What does this program print?
console.log('abc'.replace('b', '$&$&'));Answer
abbc
The reference repeats the match, so the b is written twice.
-
What does a replacement function return?
Answer
The text that takes the place of the match
The return value is converted to text and written in place of the match.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev