When working with the replace
method, if we put something in a
capturing group in a regex, then
in the replacement string we can
insert the contents of this capturing
group by writing the dollar sign
$
and the capturing group
number. For example, $1
is
the first capturing group, $2
is the second, and so on.
Why do we need this and how to use it, let's look at examples.
Example
Let's find all the numbers and replace them with the same numbers, but in parentheses. To do this, we will replace all the found numbers with the same, but in parentheses:
let str = '1 23 456 xax';
let res = str.replace(/(\d+)/g, '($1)');
As a result, the following will be written to the variable:
'(1) (23) (456) xax'
Example
Let's find all the strings that are
numbers with x's around and replace
these numbers with the same, but with
'!'
characters around:
let str = 'x1x x23x x456x xax';
let res = str.replace(/x(\d+)x/g, '!$1!');
As a result, the following will be written to the variable:
'!1! !23! !456! xax'
Example
Let's solve the following task: given
strings like 'aaa@bbb'
- letters,
then AT symbol, then letters. You need
to swap the letters before @ and after.
let str = 'aaa@bbb ссс@ddd';
let res = str.replace(/([a-z]+)@([a-z]+)/g, '$2@$1');
As a result, the following will be written to the variable:
'bbb@aaa ddd@ссс'
Practical tasks
Given a string:
let str = '12 34 56 78';
Swap the digits in all two-digit numbers.
Given a string with a date:
let str = '31.12.2025';
Convert this date to
'2025.12.31'
.