Converts a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes.
A script by V.
function spinalCase(str) { | |
// "It's such a fine line between stupid, and clever." | |
// --David St. Hubbins | |
var inputArr = []; | |
var splitIndex = []; | |
if (str.indexOf(" ") > - 1){ | |
inputArr = str.split(" "); | |
}else if (str.indexOf("_") > - 1){ | |
inputArr = str.split("_"); | |
}else{ | |
// detect uppercase letters position | |
for (var j=0;j<str.length;j++){ | |
if (str[j] === str[j].toUpperCase()){ | |
splitIndex.push(j); | |
} | |
} | |
// form array | |
for (var k=0;k<splitIndex.length;k++){ | |
var start = 0; | |
if (k === 0){ | |
start = 0; | |
}else{ | |
start = splitIndex[k-1]; | |
} | |
inputArr.push(str.slice(start,splitIndex[k])); | |
if (k == splitIndex.length-1){ | |
inputArr.push(str.slice(splitIndex[k],str.length)); | |
} | |
} | |
} | |
var dash = "-"; | |
var output = inputArr[0].toLowerCase(); | |
for (var i=1;i<inputArr.length;i++){ | |
inputArr[i] = inputArr[i].toLowerCase(); | |
output = output.concat(dash).concat(inputArr[i]); | |
} | |
return output; | |
} | |
spinalCase('thisIsSpinalTap'); |