⊗jsSpRERDP 128 of 294 menu

Default capturing groups in the replace method in JavaScript regexes

In the replace method, in addition to capturing groups with your numbers, standard capturing groups are always available: $& - entire match found, $` and $' - part of a string before and after the match. Let's see how they work with examples.

Example

Let's find all the numbers and enclose them in parentheses:

let str = '1 23 456'; let res = str.replace(/\d+/g, '($&)');

As a result, the following will be written to the variable:

'(1) (23) (456)'

Example

Let's find the @ symbol and replace it with a content before it, @ symbol, and a content after it. We write all this in parentheses:

let str = '123@456'; let res = str.replace(/@/g, "($`@$')");

As a result, the following will be written to the variable:

'123(123@456)456'

Example

Let's say we want to find a dollar symbol and wrap it in quotes ``. In this case, in order for $` not to be interpreted as a command, the dollar sign must be doubled:

let str = 'aaa $ bbb'; let res = str.replace(/\$/g, '`$$`');

As a result, the following will be written to the variable:

'aaa `$` bbb'

Practical tasks

Given a string:

let str = 'a1b2c3';

Write a regex that next to each digit will write the same one.

Given a string:

let str = 'sss site.ru zzz site.com kkk';

Replace domains with links like:

<a href="http://site.ru">site.ru</a>
nlruhudeby