(Help) Use Capture Groups to Search and Replace

This one fails one test which is the actual task of switching one two three to three two one. How do I access capture groups using $ in the replacement text? Do I use .replace() in this challenge because it seems its already there. The example shows how I can use it on the last line but we aren’t using the last line? I tried putting the $3$2$1 in the string which satisfies that condition but I feel that is totally wrong. The tried in the fixRegex to use:

let fixRegex = /(\w+)\s\1\s\2\s\3/;

But that fails the fixRegex should use at least three capture groups. So I tried this which passes all tests except Your regex should change "one two three" to "three two one". I tried looking for a couple posts about this one here but there is only one page of them. Any help? Thanks!


let str = "one two three";
let fixRegex = /(\w+)\s\1(\w+)\s\2(\w+)\s\3/; // Change this line
let replaceText = "three$3two$2one$1"; // Change this line
let result = str.replace(fixRegex, replaceText);

console.log(str)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36.

Challenge: Use Capture Groups to Search and Replace

Link to the challenge:

Hello @anonbubble,

First of all, you have to fix you current RegExp - /(\w+)\s\1(\w+)\s\2(\w+)\s\3/ - it is wrong. I suggest you to use https://regex101.com/ when you are writing regular expressions. If you test your current RegExp using it, you will see that it is wrong and is not matching one two three text. Moreover, you will see on the right side a short description of each part of your RegExp, it will help you to better understand what actually your RegExp is trying to match or why it is not working as you want/expect.

Second is that you are using replaceText the wrong way. To better understand how should it look and how to use it I suggest you to check the docs - MDN. There you will find at least the following:

$n => Where n is a positive integer less than 100, inserts the n th parenthesized submatch string, provided the first argument was a RegExp object. Note that this is 1 -indexed. If a group n is not present (e.g., if group is 3), it will be replaced as a literal (e.g., $3 ).

To cut a long story short, $1 is what your first matching group matched, $2 - the second group match and so on. In this task your replaceText should not contain three, two, one strings. It should consist of matched groups only - $n.

And instead of console logging str you should console result.

Let me know if you have other questions. :slight_smile:

1 Like