Need explanation of capture groups

Need explanation of capture groups
0

#1

Tell us what’s happening:

Your code so far


let repeatNum = "42 42 42";
let reRegex = /change/; // Change this line
let result = reRegex.test(repeatNum);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/reuse-patterns-using-capture-groups


#2

What kind of explanation are you seeking?


#3

I don’t understand what I’m being asked to do, and also the explanation of capture groups doesn’t make sense to me. I don’t understand why this works the way it does : let repeatStr = “regex regex”;
let repeatRegex = /(\w+)\s\1/;
repeatRegex.test(repeatStr); // Returns true
repeatStr.match(repeatRegex); // Returns [“regex regex”, “regex”]


#4

Probably regurgitating the instructions, but you being asked to use capture groups to satisfy the test.

basically how capture groups work is that the stuff you match within the parenthesis “( )”, are sort of stored in a temporary array. You can then access whatever you match with that capture group with in index, starting at 1.

so in the example:

let repeatStr = “regex regex”;
let repeatRegex = /(\w+)\s\1/;
repeatRegex.test(repeatStr); // Returns true
repeatStr.match(repeatRegex); // Returns [“regex regex”, “regex”]

The regex is first finding something that matches the longest string of word characters. Then find a space. Then, instead of typing out the match again, simply reuses the match with \1.
Now if you’re wondering about the last line, that’s just the nature of what match returns.


#5

Thank you, I managed to solve it after understanding that the match was reused with \1