Intermediate Algorithm Scripting: Spinal Tap Case_Help Requested

Intermediate Algorithm Scripting: Spinal Tap Case_Help Requested
0

Hello. I wondered if I could get some help understanding something. In the following code, I don’t understand what exactly str = str.replace(/([a-z])([A-Z])/g, '$1 $2'); does. The explanation (Replace low-upper case to low-space-uppercase) doesn’t make sense to me. Thanks in advance!

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();
}

// test here
spinalCase('This Is Spinal Tap');

Hi @ksirgey,

You can refer the below link for explanation.
https://www.freecodecamp.org/forum/t/spinal-tap-case-operator/56148

1 Like

/([a-z])([A-Z])/ this matches a lower case character followed by an upper case character. This is what is going to be replaced
'$1 $2' This is what is going to be put in place of the previous: $1 match the first parenthesis (), $2 match the second one, with an extra space in between

1 Like

Okay, I don’t know what level of “not understanding” you have, so I apologize if I tell you something you do understand. :slight_smile:.

([a-z]) and ([A-Z]) are capture groups. Each (something inside parens) tells the regex you want to save the match. And the g a the end tells regex you want to do it for all the matches in your string, not just the first one (g stands for global here)

You are telling regex that you want to catch a lowercase character a thru z and save it and you want to do the same for an uppercase character A thru Z. but because they are side by side like this ([a-z])([A-Z]) you want it to capture a lowercase a thru z that is right before an uppercase A thru Z and an uppercase A thru Z that is right after a lowercase a thru z. Following?

So, now we have our two capture groups, what do we do with them? We are going to use the String.replace() string method to change str. $1 is like a variable referring to your first capture group in you regex and $2 refers to your second group and so on. You could say that before the replace did its thing your capture groups looked like this in str: '$1$2'. They are right next to each other cause that is what you were grabbing as I explained in the second paragraph. But you are telling String.replace() that you want to replace that with '$1 $2', putting a space between them.

Thus, 'iAmCamelCase'.replace(/([a-z])([A-Z])/g, '$1 $2'); would equal 'i Am Camel Case'.

I hope that helped.

3 Likes

Thanks so much! I get it now. :slight_smile: