Can Anyone Explain. What is the "$1 $2" in first replace statement of solution 1?

Continuing the discussion from freeCodeCamp Challenge Guide: Spinal Tap Case:

2 Likes

It’s the first and the second capturing groups.

In regex, you can put a pattern in brackets (()). The brackets specify a capturing group: whatever matches in that group is “captured”, and then you can use $1, $2 etc to access the first, second etc groups.

/([a-z])([A-Z])/g

So this captures

  1. one character a-z,
  2. one character A-Z

If the whole pattern matches, you can then use the reference to the relevant capturing group

str = str.replace(/([a-z])([A-Z])/g, "$1 $2");
9 Likes

Dan thanks for this awesome explanation.

That was a fine explanation but could you elaborate more on how it works in the context of this question?

$1 is the end of one word, $2 is the start of the other word, replace add a space in between

3 Likes
str = str.replace(/([a-z])([A-Z])/g, "$1 $2")
                      ↑      ↑
                     $1     $2

So if str is “aB”, that matches (lowercase a-z character followed by uppercase A-Z character), first capturing group is the lowercase, second capturing group is the uppercase, so it will be replaced with “a B”

So if str is “helloThere”, that matches (there is lowercase a-z character followed by uppercase A-Z character), first capturing group is the lowercase, second capturing group is the uppercase, so it will be replaced with “o T”.

So if str is “hello”, that doesn’t match (lowercase a-z characters are only ever followed by another lowercase character)

11 Likes

I as well had a hard time understanding this. Your explanation definitely helps, thanks.

Is the most clear explanation, it has helps me.
Thanks!

wow, this really helps.

@DanCouper you have given examples like “aB” and “helloThere” that are both examples of lowercase letter followed by uppercase letter and the pattern for this was ([a-z])([A-Z]) but why does this pattern also work for strings like “HelloWorld” where uppercase letter is followed by lowercase?

HelloWorld
    --

The uppercase followed by lowercase isn’t the pattern being matched, nothing else is relevant in the string except the lowercase-followed-by-uppercase pair of characters

HELLoworld

:point_up: Won’t match, if there is no one-lowercase-followed-by-one-uppercase pair, nothing matches

1 Like

i think i finally got it thanks!

1 Like