Reuse Patterns Using Capture Groups caret and dollar sign?

Tell us what’s happening:

I’m trying to understand why it’s necessary to put the caret (^) at the beginning and the dollar sign at the end ($). I managed to do all the challenge but those last two things I saw was in the hint and when I saw them, I stayed loading.

Your code so far

let repeatNum = "42 42 42";
let reRegex = /^(\d+)\s\1\s\1$/; // Change this line
let result = reRegex.test(repeatNum);
let result2 = repeatNum.match(reRegex);

Your browser information:

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

Link to the challenge:

1 Like

If you used .match and the .length === 1 assertion the challenge would’ve been solved as a function but since in this case you have some guarantees you only need the caret and the sign because:

1- You are guaranteed that the entire string only has numbers separated by spaces and nothing surrounding those numbers on both sides.
2- There’s always 1 space between numbers

So the pattern reads as follow

  • First match the beginning of the string
  • Then search for 1 or more digits together and save it as capture group #1
  • Match a space
  • Match the same number again referring to it as \1
  • Match a space
  • Match the same number again referring to it as \1
  • Finally, match the end of the string

This way you can assure that there’s no repetitions at the extremes of the string.


So, they are used to mark the beginning and end of the regex, right?

Es decir que sirven para marcar el comienzo y el final del regex, no? E

Español para ti, inglés para la comunidad jajajaja

Sí, para eso sirven

Yes that’s what they are for.

^ - Start
$ - End