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');
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