Continuing the discussion from freeCodeCamp Challenge Guide: Spinal Tap Case:
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
- one character a-z,
- 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");
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
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)
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
Won’t match, if there is no one-lowercase-followed-by-one-uppercase pair, nothing matches
i think i finally got it thanks!