Regex query, using capture groups

Tell us what’s happening:

As per the solution, can someone please explain the use of ‘$’. I understand that it is used for capture groups but how does it work in the case of this problem?

Your code so far


function spinalCase(str) {
// console.log(str.replace(/\W/g, ''))
let newStr = str.replace(/([a-z])([A-Z])/g, '$1 $2')
console.log(newStr)
return newStr.replace(/\s+|_+/g, "-").toLowerCase();
}

spinalCase('This Is Spinal Tap');
spinalCase("Teletubbies say Eh-oh")
// spinalCase("AllThe-small Things")

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0.

Challenge: Spinal Tap Case

Link to the challenge:

Hello @shaurya26,

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:

  1. 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.
  2. 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.

You can use https://regex101.com/ to check your RegExp on some random typed strings.

2 Likes

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