How does this solution work? (Regex)

solution

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);

What I don’t understand is how “$3 $2 $1” is able to work. Does $ just automatically refer back to the regex being used in the replace function? What if you wanted to replace with the literal string that contained the dollar sign? i.e “$4 $6 $1”

The parenthesis create capture groups, which are then accessed with $1, $2, $3 (first second, third capture group).

3 Likes

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