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.