Failing to match globally a regex that uses a variable

I am almost done with the exercise bellow.

I am using an ugly approach, I know… But, I am almost there!

The code bellow passes on all test cases except for:
spinalCase("thisIsSpinalTap") should return "this-is-spinal-tap" .

This happens because I am unable to use the match globally as //gon this line:

var fix_str = no_under_score.replace(char,"-"+String(char));

How would you fix this?

Your code so far



function spinalCase(str) {
  //let lower_str = str.toLowerCase();
  let no_white_space = str.replace(/\s/g, '-');
  let no_under_score = no_white_space.replace(/_/g,"-");

  for (let index in no_under_score) {
      var char = no_under_score[index];
      //console.log(no_under_score[index]);
      if (char==char.toUpperCase() && index!=0&& char!="-") {
          //console.log(char);
          var before_char = no_under_score[index-1];
          //console.log(before_char);
          if (before_char!="-") {
              //console.log(before_char)
              var fix_str = no_under_score.replace(char,"-"+String(char));
              return fix_str.toLowerCase();
          }
          
      }
  }
  return no_under_score.toLowerCase();
}


spinalCase('This Is Spinal Tap');

Your browser information:

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0.

Challenge: Spinal Tap Case

Link to the challenge:

Thanks in advance!

I tried another approach, which is definetly not elegant but it worked!


function spinalCase(str) {
    let alt_str = "";
    for (let index in str) {
        let char=str[index];
        if (char=="_" || char==" ") {
            alt_str +="-";
        }
        else if (char==char.toUpperCase() && index!=0) {
            alt_str+="-"+char
        }
        else {
            alt_str+=char
        }

    }
    let semi_final = alt_str.toLocaleLowerCase()

    let final = semi_final.replace(/--/g,"-")
    return final
}```