I need help understand this regex

Continuing the discussion from freeCodeCamp Challenge Guide: Spinal Tap Case:

Here’s the code:

function spinalCase(str) {
  // Replace low-upper case to low-space-uppercase
  str = str.replace(/([a-z])([A-Z])/g, "$1 $2");
  // Split on whitespace and underscores and join with dash
  return str
    .split(/(?:_| )+/)

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

I don’t understand this regrex expression: .split(/(?:_| )+/)

First: what is the question mark before the colon "?: " means? (i couldn’t find in the material);
Second: there’s nothing after the “or” expression “|”, or is that a space after it?
Many thanks.

You should get in the habit of researching and tinkering.

Also, regex is weird.

When confronted with regex, I often hop over to a site like regex 101 and mess around with it. You can put in your regex and mess around with it. The “?:” is a bit of an oddball, but if I google “regex ?:”, explanations pop up.

Being able to research and figure things out is a very important skill for a developer. Professional developers are googling things several times a day. I’m an hour into my work day and I have spent at least half of that googling and reading things trying to figure out how to solve my issue.


Thank you for your suggestion. Now that I dig deeper into this, I found some problems with all these solutions:

It won’t remove the blank or any other non-word characters at the start of the string. Eg: the string “–This Is Spinal Tap” would return “–this-is-spinal-tap”.
I found the solution to this:

function spinalCase(str) {
  return str
  .replace(/^\W+/, "")

console.log(spinalCase('--This Is Spinal Tap'));
// this-is-spinal-tap

We like to obscure working solutions to challenges so I added [spoiler][/spoiler] tags.

Yeah, the possible inputs are not clearly defined, so I agree that your solution is more robust.

Keep in mind that the solutions aren’t very well maintained so you have to take them with a grain of salt. Personally, I wish we’d just get rid of them.

1 Like

I agree, I think it would encourage the research and tinkering as you mentioned too, instead of just looking at the solutions and moving on to the next challenge.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.