this is the example given as an explanation to the lesson:
let repeatStr = "row row row your boat";
let repeatRegex = /(\w+) \1 \1/;
repeatRegex.test(repeatStr); // Returns true
repeatStr.match(repeatRegex); // Returns ["row row row", "row"]
the question is after I understood that I can access the substring matched by using the number of the capture group that matched it, in this case, it’s \1. why in the regex of the example they used two \1s: /(\w+) \1 \1/ ?(this interrogation mark is for my question, not part of the regex I’m stating).
thank you.
`let repeatNum = "42 42 42";
let reRegex = /(\d+)(\s)\1\2\1/; // my solution
let result = reRegex.test(repeatNum);
console.log(result);
let res = repeatNum.match(reRegex);
console.log(res);
`
and the hint page solution:
let reRegex = /^(\d+)\s\1\s\1$/; // this has passed the challenge
how in their solution they could use caret and dollar signs in the same regex? matching beginning and end of the string , and why?
You can use both ^ and $. In fact, you often do. If you want to make sure that there is nothing else before your pattern and nothing else after your pattern, then you need to specify the beginning and end of the string.