Help Understanding Spinal Tap Challenge Solution

Help Understanding Spinal Tap Challenge Solution
0

#1

Hi all!

I’m working through the intermediate algorithm challenges and one of the solutions that was offered by @thegreaterpanda looks really elegant, but I don’t understand how the last part of the .replace method’s syntax works.

Here is his code:

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

So far, this is my understanding of that code:

  • Return the result of the replace method called on the string argument (thereby creating a new “str”),
  • For every lower case a to z letter (RegExp), every capital A-Z letter (RegExp) -OR- underscore or blank space characters of at least one or more, global search…
  • …and then the syntax for the $1 and $2 I don’t understand.

The MDN documentation says that $n takes any positive integer below 100 and assigns it to the nth “parenthesized submatch string”, assuming that the first argument fed to .replace is a RegExp object.

So, with the above syntax, I am guessing it would read: for every capital or lower case a-z OR a blank space/underscore, replace it with… that same letter or blank space? I’m really not sure. :confused:


#2

replace(/([a-z])([A-Z])/g, '$1-$2')
matches lowercase letter followed by uppercase letter and separates them with -
example:
aB => a-B

replace(/[_|\s]+/g, '$1-$2')
matches sequence of _ or space and replaces it with -
example:
_ => -
<space> => -

https://www.mariadcampbell.com/2016/06/27/spinal-tap-case/


#3

Ah, that makes sense. So the RegExp paramter of the .replace method actually reads continuously as:

“For every lowercase a-to-z followed by a capital A-to-Z” , rather one or the other.

And the “$1-$2” acts as the replacement which will insert a “-” character inbetween.

Thank you for the explanation @marzelin! :slight_smile: