RegEx back-referencing as a replacement

Tell us what’s happening:

Hi, so I found this very elegant RegEx solution to the Spinal Tap Case challenge. I’ve managed to dissect the solution to find why it works, but I still have one question.

I understand that ‘$1-$2’ is a back-reference meant to place a dash between capture groups 1 and 2. But how does this work with the character set [_\s]? How does back-referencing $1 and $2 in the replacement tell replace() to put a dash where there are spaces or underscores? This character set is not in the two capture groups.

  **Your code so far**

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

console.log(spinalCase('ThisIsSpinalTap'));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36.

Challenge: Spinal Tap Case

Link to the challenge:

There are two possible matching scenarios here:

  • ([a-z])([A-Z]) in which $1 is the first capture and $2 is the second.

  • [_\s]+ in which $1 and $2 are empty because there are no captures.

So in the first one, $1-$2 will be whatever was captured in the first parens, then a dash, then what ever was captured in the second parens.

For the second one, $1-$2 will be empty string, then a dash, then empty string, or just -.

2 Likes

That explains it! Thank you :slight_smile: