How can I fix the regex, in order not to have double dashes "--"

Tell us what’s happening:
I ram out of ideas to solve this.
My print is this:

-teletubbies-say–eh-oh
this-is-spinal-tap
-the–andy–griffith–show
-all-the-small–things

Im my mind I can’t lowerCase before the regex, because I lose the reference to add "- " before the CAPS letters.
Any ideias?

Your code so far

js

function spinalCase(str) {
// "It's such a fine line between stupid, and clever."
// --David St. Hubbins
 return str.trim().replace(/\s|_|(?=[A-Z])/g, "-").toLowerCase()

}

spinalCase('This Is Spinal Tap');

Your browser information:

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

Challenge: Spinal Tap Case

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/spinal-tap-case

your regex capture both the space and the upper case letter, so if you have a space followed by a upper case letter, both will get the dash. I think you could change the look ahead to capture something only if it is not preceded by a space.

or add a look behind that will check of the upper case letter is preceded by an other letter, so you can also fix the dash at the beginning

1 Like

I managed, but in a very amateur way:


function spinalCase(str) {
  
  const x = str
.replace(/\s|_|(?=[A-Z])/g, "-")
.toLowerCase()
.replace(/--/g, "-").replace(/^-/,"")
  return x 
}

Not fully happy with how this looks . I’ll try your ideas next, and see if I manage!

Done,
thanks to your inputs:

function spinalCase(str) {

  const x = str
    .replace(/\s|_|\W(?=[A-Z])|(?<=[a-z])(?=[A-Z])/g, "-")
    .toLowerCase()
  return x
}

You actually do not need the extra x variable. Also, you are repeating the following:

(?=[A-Z])

You can remove this duplication by making a slight change in the regex.