The content of the capturing groups is available not only in the replacement string, but also in a regex itself: we can put something in a capturing group, and then directly in the regex say that the content of this capturing group should be here.
The contents of the capturing groups
are available by their numbers, which
are preceded by a backslash. For example,
the first capturing group will be
available like this: \1
, the
second one like this - \2
,
the third - \3
and so on.
I am sure that everything written above is still very vague for you. This is not surprising, since such capturing groups are the most obscure place in regexes. Let's look at examples.
Example
Let's say we have a string like this:
let str = 'aa bb cd ef';
Let's find in it all the places in which there are any two identical letters in a row. To solve the problem, we'll look for any letter, put it in a capturing group, and then check if this content is the next character:
let res = str.replace(/([a-z])\1/g, '!');
As a result, the following will be written to the variable:
'! ! cd ef'
Example
Let's say we have a string like this:
let str = 'asxca buzxb csgd';
Let's find in it all the words in which the first and last letters are the same. To solve the problem, write the following pattern: a letter, then one or more letters, and then the same letter as the first one:
let res = str.replace(/([a-z])[a-z]+\1/g, '!');
As a result, the following will be written to the variable:
'! ! csgd'
Practical tasks
Given a string:
let str = 'aaa bbb ccc xyz';
Find all substrings that have three identical letters in a row.
Given a string:
let str = 'a aa aaa aaaa aaaaa';
Find all substrings that have two or more identical letters in a row.
Given a string:
let str = 'aaa aaa bbb bbb ccc ddd';
Find all substrings that have two identical words in a row.