Regular Expressions: Use Capture Groups to Search and Replace

There is a test that I still nedd to pass: Your regex should change "one two three" to `“three two one”.

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


https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/use-capture-groups-to-search-and-replace

Hello, santiago.

You have a few issues in your solution:

  1. Have a rethink about your regex. It will not match what you want.
  2. Have a look at the capture group syntax used:
"Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1')
  1. Think about what the numbers represent, for the capture groups.

console.log() a few things to see what is happening at each stage.

Hope this helps

2 Likes

It is done, thanks!

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);
console.log(result);