Spinal Tap Case Help

Spinal Tap Case Help
0

#1

My…“solution”…only gives me a dash in the first space. I know I could make this work by splitting up the string into an array, but how do I replace the all of the spaces in the string in place?

Me code:

function spinalCase(str) {
  var test,
      newStr;
  
  for (var i = 0; i < str.length; i++) {
    test = /\w/gi.test(str[i]);
    if (test === false) {
      newStr = str.replace(str[i], '-');
    }  
    
  }
  
  return newStr;
}

spinalCase('This Is Spinal Tap');



#2

Hey, you don’t need a for loop at all
So I’d like to give you an idea of what you could do:

First, you replace all capital letters with a space plus that capital letter. The g means global so it will go through the whole string looking for a capital letter
str = str.replace(/[A-Z]/g, function(cap){return ’ ’ + cap;});

‘This Is Spinal Tap’ becomes ’ This Is Spinal Tap’

then change everything to lower case
str = str.toLowerCase();

then now you can now remove all spaces and replace them with -'s. This code replaces every space or consecutive set of spaces(remember that their will be double spaces between some words now because we replaced capital letters with a space + the capital letter. The + in the code below ensures double spaces are treated as one space ie are replace with one dash), with -

str = str.split(/[^a-zA-Z0-9]+/).join(’-’);

now your str becomes ‘-this-is-spinal-tap’

now I’ll leave you to figure out how to remove the first - if str has one


#3

From String.replace() documentation:

Only the first occurrence will be replaced.

What you are doing every time is this:
newStr = str.replace(' ', '-')
replace finds first occurrence of a space and replaces it with dash. Every time.


#4

Thanks for your replies, this is what I came up with:

function spinalCase(str) {
  var caps,
      splitter;
  
  caps = str.replace(/\b[a-z]/g,function(f) {
    return f.toUpperCase();
  });
  
  splitter = caps.match(/[A-Z][a-z]+/g);
  
  return splitter.join('-').toLowerCase();
}

spinalCase('thisIsSpinalTap');