As far as I understood you are asking about this line of code: let newStr = str.replace(/([a-z])([A-Z])/g, '$1 $2')
Your regexp /([a-z])([A-Z])/g will match lowerCase letter followed by upperCase letter. So if you have string like lower Case test, you will not have matches here. Since there are no cases, when lower case letter is followed by an upper case letter. If you have string like ‘lowerCaseTest’ then regexp will match here two times: rC, eT. Now, r letter is a first or 1 matched group and C letter is the second or 2 matched group. The same is about e and T letters.
From MDN docs you will see that $n means: $n => Where n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. Note that this is 1-indexed. If a group n is not present (e.g., if group is 3), it will be replaced as a literal (e.g., $3).
So, your replace() function is doing the following things:
it looks the pattern in a string you’ve described with RegExp. In your case pattern is a regular expression - /([a-z])([A-Z])/g. And string is a str variable or its actual value.
in case the pattern is found, it replaces the matched pattern of $1$2 with a string like $1 $2. It just puts space between them.
That why, if str value was like ‘simple Camel Case Variable’ you will not see any changes, because there are no matched. But if your value is like simpleCamelCaseVariable, you will see that the newStr will be like simple Camel Case Variable.
Thank you for the clear and thorough explanation!
I had read the MDN docs and just needed a little more clarity which you rightfully provided. Thank you!
When I asked this on Stack Overflow, I was downvoted to oblivion xD