Spinal case, regex

Tell us what’s happening:
Why can’t the third line replace the code in the comments? I dont understand why a space can be used to replace anything other than a alphanumerical, but not a hypen.

(this is not my original solution; just was trying some things out)

Your code so far


function spinalCase(str) {
return str.replace(/([A-Z])/g,' $1')
  .replace(/[^A-Za-z0-9]/g, '-')
  /*
  .replace(/[^A-Za-z0-9]/g, ' ')
  .replace(/\s{1,}/g, "-")
  */
  .replace(/^\-|[\-]$/g, '')
  .toLowerCase();
}

spinalCase('AllThe-small Things');

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36.

Challenge: Spinal Tap Case

Link to the challenge:

You question reads quite confusing to me. Would you mind rephrasing it and be more specific?

Yes, my apologies.
Lets say these 2 lines of code is number1 and the 1 line below it is number2.

number 1:
.replace(/[^A-Za-z0-9]/g, ’ ')
.replace(/\s{1,}/g, “-”)

and
number 2:
.replace(/[^A-Za-z0-9]/g, ‘-’)

Both of these seem to be doing the same exact thing, which is ultimately replacing any non-alphanumberical with a hyphen, but number 2 has one less line of code. When used in my function, number1 does return the correct solution, but number2 does not. Why is this?

In this line, a white space is inserted before $1:

return str.replace(/([A-Z])/g,' $1')

.replace(/[^A-Za-z0-9]/g, '-') replaces each non alphanumeric character with a dash.

.replace(/\s{1,}/g, "-") replaces any number of consecutive spaces with a single dash.

1 Like

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