Regex:Capturing Groups

let str = "AllThe-small Things"
str = str.replace(/([a-z])([A-Z])/g, "$1 $2");
console.log(str); 
**// output is:All The-small Things**

*What difference between those two code blocks? Normally, I know I have 3 capture groups on that sample. The one is for lower case the other is for uppercase and the last one is for the main string. But, I didn’t understand that groups clearly.What I am missing here? *

let str = "AllThe-small Things"
str = str.replace(/([a-z])([A-Z])/g, "$2 $1");
console.log(str); 
**// output is:AlT lhe-small Things**

there is only two capture groups, what’s the third one you are referring to?

1 Like

$0 that one whole string

that’s not a capture group, that is the new text that is being inserted in the string in place of what the regex matched

$1 and $2 let you use what was captured by the capture groups in the new string, $1 is a placeholder for what the first capture group has captured, and $2 for the second one

in the string the regex matches lT, where l is captured by the first group and T by the second
"$1 $2" results in "l T" and "$2 $1" in "T l"

1 Like

You mean ,first capturing groups should be lower case and second group should be upper case for first case code.(str.replace(/([a-z])([A-Z])/g, “$1 $2”). if str is “AllThe-small Things” for first case I should to find lower cases ? Because for “All” the ‘A’ is uppercase but still it can come first with group. I confused so much :slight_smile: Thanks…

Thanks for the quick answer. I understood now. I was confused about that white space :slight_smile: between those groups($1 $2) has also space I have missed that white space.

No, so the regex finds any* pairs of a lowercase letter ([a-z]) directly followed by an uppercase letter ([A-Z]).

The pattern is /[a-z][A-Z]/, that’s two characters.

So in the string “AllThe-small Things”, there is one instance of that, “lT”:

AllThe-small Things
   ↑
here

The pattern to find each of those is wrapped in brackets

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

That’s two capture groups.

/([a-z])([A-Z])/
   ↑
capture group 1
/([a-z])([A-Z])/
          ↑
capture group 2

Or

/([a-z])([A-Z])/
    ↑       ↑
    $1      $2

Then the second argument to replace is “$1 $2”, so whatever $1 is then a space then whatever $2 is.

In “AllThe-small Things”, the only match is “lT” (lowercase l followed by uppercase T), so for that match, $1 is l and $2 is T, so replace “lT” with “l T”.


* the g flag at the end means global, ie find all instance of the pattern, that’s why it’s any.

1 Like

Thank you , I really appreciate it for your great explanation … I totaly understood :slight_smile:

1 Like