Reuse Patterns Using Capture Groups Explained Simply

Ok so this lesson is easy but they explain it in a stupid way that makes it difficult.

So imagine you want to match

abc123abc123

you could match it like this…

/(abc)(123)(abc)(123)/    

but what is you don’t feel like typing (abc) and (123) twice?

well then you can reference the first times you typed them to save your fingers! Javascript would ‘label’ them like this.

   \1   \2   \3   \4         //top line is the labels.
 /(abc)(123)(abc)(123)/   

so insted I can just write

/(abc)(123)\1\2/  

\1 references what is inside the first set of () ie abc
\2 references what is inside the second set of () ie 123

one more example.

If I wanted to match

xyz xyz xyz abc abc xyz abc

I could use

/(xyz)\s\1\s\1\s(abc)\s\2\s\1\s\2

in this example \1 is equal to xyz,
\2 is equal to abc.

Hopwe this helps.

hi, do you want to suggest a change to the guide article about this challenge?

1 Like

Both, yours and challenge descriptions are equally fine to me personally. What exactly do you find stupid?