Spinal Tap Case Help with dashes when no space

Spinal Tap Case Help with dashes when no space
0

#1

Hi guys. I’m most of the way there with this. The only thing I can’t figure out how to do is add a dash when there’s no spaces (ie the words are joined up). I’ve been struggling over this for ages and cant find an answer anywhere so just need someone to push me in the right direction please! Many thanks in advance

function spinalCase(str) {
  // "It's such a fine line between stupid, and clever."
  // --David St. Hubbins
  var newStr = "";
  
  for (var i=0; i<str.length; i++) {
    if (/[\s_]/.test(str[i])) { //turn space into dash and append to new string
      newStr += "-";
    } else if (/[A-Z]/) { // turn capital into lowercase and append to new string
      newStr += str[i].toLowerCase();
    } else { // append rest to new string
      newStr += str[i];
    }
  }
  
  return newStr;
}

spinalCase("thisIsSpinalTap");

#2

I usually give only hints, but this time I don’t know how to hint :wink:

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

#3

How about you don’t turn capital letters into lower case immediately, you put a space before the capital letter first

str = str.replace(/[A-Z]/g, function(cap) {return ’ ’ + cap;});

ie thisIsSpinalTap becomes “this Is Spinal Tap”

then change everything to lower case and simply replace a space or bunch of consecutive spaces with a single dash


#4

Perfect, thanks guys I got it :slight_smile: