Why wont this code work when i treat \s as a capture group?

Tell us what’s happening:

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

let matchResult=str.match(fixRegex);

Your browser information:

User Agent is: Mozilla/5.0 (Linux; U; Android 7.0; TECNO P701 Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/64.0.3282.137 Mobile Safari/537.36 OPR/52.1.2254.54298.

Challenge: Use Capture Groups to Search and Replace

Link to the challenge:

Hello there,

For future posts, please make use of the Tell us what’s happening section of the post to ask your question/give useful information.

Just to clarify what is happening:

  • replace accepts 2 arguments
    – The text/regex used to match
    – The pattern/text used to replace what is matched
  • fixRegex matches:
    \w+ One or more word-characters
    \s whitespace
    \w+ One or more word-characters
    \s whitespace
    \w+ One or more word-characters
    – The parentheses () act as a capturing group
  • replaceText contains the pattern to match:
    $3 the 3rd element matched
    $2 the 2nd element matched
    $1 the 1st element matched

Now, using this code:

const str = "one two three";
const mat = str.match(/(\w+)(\s)(\w+)(\s)(\w+)/);

mat consists of an array of the patterns matched (as well as some other information:

[ 'one two three',
  'one', // The first capture group
  ' ', // The second capture group
  'two', // The third capture group
  ' ', // The fourth capture group
  'three', // The fifth capture group
  index: 0,
  input: 'one two three',
  groups: undefined ]

So, using the pattern $3 $2 $1 will lead to: 'two one' (notice, there are 3 spaces in this match)

Hope this clarifies

Am sorry I didn’t drop my explanation alongside the topic.
Before passing the challenge I used /(\w+)(\s)(\w+)(\s)(\w+)/ as my regex but it didnt work. then i tried removing the brackets around \s and it worked. Now i dont understand why the former would not work.

That is what I understood, from your post.

Let me summarise:

  • Parenthases () are a capture group
  • Capture groups are matched by the patterns $1
  • Therefore, if \s is in a capture group, the pattern $2 will match \s which is a space.
  • If \s is not in a capture group, then it is not matched by any patterns.

Hope that helps

1 Like

A big thanks to you. I understand it better now.