Intermediate Algorithm Scripting - Spinal Tap Case

Tell us what’s happening:

I do not understand how the second line of the solution code works, even after reading the description why. Can someone further explain to me how this works?

My understanding is that the parenthesis create capture groups that can be referenced later for replacement. So I see a capture group for lowercase letters and a capture group for upper case letters. In the replace, we specify this regex and then replace it with each capture group, which I see as the lowercase letters and then the upper case letters.
I do not understand how a space is then put in between the capital and lowercase letters going from

AllThe

to

All The...

Your code so far

function spinalCase(str) {
  // Create a variable for the white space and underscores.
  var regex = /\s+|_+/g;

  // Replace low-upper case to low-space-uppercase
  str = str.replace(/([a-z])([A-Z])/g, "$1 $2");

  // Replace space and underscore with -
  return str.replace(regex, "-").toLowerCase();
}

console.log(spinalCase("AllThe-small Things"));

// test here

Code Explanation

  • regex contains the regular expression /\s+|_+/g, which will select all white spaces and underscores.
  • The first replace() puts a space before any encountered uppercase characters in the string str so that the spaces can be replaced by dashes later on.
  • While returning the string, another replace() replaces spaces and underscores with dashes using regex.

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36

Challenge Information:

Intermediate Algorithm Scripting - Spinal Tap Case

str.replace(/([a-z])([A-Z])/g, "$1 $2")
  • Replace matches every case when there’s lowercase letter followed by uppercase letter. Each to own capture groups
  • Then it is replaced by "$1 $2":
    • First group - $1 - lower case letter.
    • Space
    • Second group - $2 - upper case letter.
1 Like