Antonio Ortiz Antonio Ortiz - 7 months ago 48
Javascript Question

How do I convert a string to spinal case in JavasScript?

I am stuck on this coding challenge Spinal Tap Case from freeCodeCamp. Essentially I don't know how to get the last check to execute.

This is the last check:

spinalCase("AllThe-small Things") should return "all-the-small-things"


And this is my code:

function spinalCase(str) {
var outputString,
newstr,
pattern1 = new RegExp(/[_\s]/, 'g'),
pattern2 = new RegExp(/(?=[A-Z])/, 'g'),
stringTest1 = pattern1.test(str),
stringTest2 = pattern2.test(str);

if(stringTest1) {
outputString = str.replace(pattern1, '-');
newstr = outputString.toLowerCase();
} else if(stringTest2) {
str.split(/(?=[A-Z])/).join(' ');
outputString = str.replace(pattern2, '-');
newstr = outputString.toLowerCase();
} else if (stringTest1 && stringTest2){
outputString = str.replace(pattern1, '-');
outputString = str.replace(pattern2, '-');
newstr = outputString.toLowerCase();
}

return newstr;

}


I do realize the last
else if
condition should go first however I didn't get the syntax right.

Thanks in advance!

Answer

Here is how I recommend doing it:

function sp(str) {
  var spinal = str.replace(/(?!^)([A-Z])/g, ' $1')
                .replace(/[_\s]+(?=[a-zA-Z])/g, '-').toLowerCase();
  return spinal 
}

JsBin Example

as far as your code, you check for:

if test1 else if test2, then else if test1 and test2, the logic is not correct:

you could try to adding a !test2 or !test1 to the first if checks to get it working:

if (stringTest1 && !stringTest2)...

EDIT:

here is how you can get your code to fire in that last else if, I put a console.log in there to show you here:

JSBin Example

function spinalCase(str) {
    var outputString, 
              newstr,
              pattern1 = new RegExp(/[_\s]/, 'g'),
              pattern2 = new RegExp(/(?=[A-Z])/, 'g'),
              stringTest1 = pattern1.test(str),
              stringTest2 = pattern2.test(str);

         if(stringTest1 && !stringTest2)  {
                outputString = str.replace(pattern1, '-');
                newstr = outputString.toLowerCase();
          } else if(!stringTest1 && stringTest1) {
               str.split(/(?=[A-Z])/).join(' ');
                outputString = str.replace(pattern2, '-');
                newstr = outputString.toLowerCase();
          } else if (stringTest1 && stringTest2){
                console.log('were in the last else!!!');
                outputString = str.replace(pattern1, '-');
                outputString = str.replace(pattern2, '-');
                newstr = outputString.toLowerCase();
          }

  return newstr;

}