Regular Expressions - Use Capture Groups to Search and Replace

Tell us what’s happening:
Describe your issue in detail here.
what does $ actually do in this case?
Could someone explain me?

Your code so far

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

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36

Challenge: Regular Expressions - Use Capture Groups to Search and Replace

Link to the challenge:

The exercise describes what the $ is for

You can also access capture groups in the replacement string with dollar signs ($).

"Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1');

The replace call would return the string Camp Code.

So the $2 maps to the 2nd capture group in the example, and $1 maps to the first capture group in the example.

the arrows between second and third line are not correct, $3 references the third capture group, not the first one

image

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.