Using RegEx capture groups with replace() in JS
NicolasBrondinBernard
The `replace()` method is natively designed to be used with regular expressions. Let's take a look at how to do it!

Article published on 26/06/2023, last updated on 10/08/2026
A regular expression allows you to detect a "pattern" in a character string, to extract it from the text with the RegEx.exec(...) method, or to replace the content using the String.replace(...) method.
But what isn't always known is that when using a regular expression with String.replace(...), it is possible to reinject part of the data found by the regular expression into the final result.
Capture groups
Let's take a very simple regular expression, to separate the two parts of an email address:
const exp = /(.*)@(.*)/gm;
Obviously, this is just an example, it is too simple to actually detect an email address in a text.
The parts of this expression that are between parentheses are called "capture groups". This means they will be detected when using the RegEx, and they will be returned in the result:
const exp = /(.*)@(.*)/gm;
exp.exec(email);
/*
[
'code@example.com',
'code',
'example.com',
...
]
*/
The first element of the array represents the full string, and the following elements represent the captured groups (here "code" and "example.com").
But let's now see how to reuse them with String.replace(...)
Usage with replace()
To inject the capture groups into the result of a string replacement, you just need to use the "$" character followed by the group's index. So:
- $1 will correspond to "code"
- $2 will correspond to "example.com"
With our example code, this gives the following:
const exp = /(.*)@(.*)/gm;
const email = "code@example.com";
const result = email.replace(exp, "$1[at]$2");
console.log(result); // code[at]example.com
And there you go, you now know how to combine the use of capture groups from a regular expression with the replace() method!
Complete courses, exercises and certificates to really learn programming!
4.8 average rating
No comments yet