Due to an excercise, I've made a function that converts given string to spinal case just-like-this-one
(all lower case).
I did it with two regular expressions. Can it be done with one, or generally better?
function spinalCase(str) {
//if string is not delimited
if(str.search(/[_\s]/) === -1){
// insert dash before every uppercase letter
return str.replace(/(?=[A-Z])/g , '-').toLowerCase();
} else {
//change delimiters to dashes
return str.replace(/[_\s](?=[a-zA-Z])/g, '-').toLowerCase();
}
}
edit: variable naming was forced by excercise (wouldn't complete otherwise). Example converted input:
"This Is Spinal Tap"
"thisIsSpinalTap"
"The_Andy_Griffith_Show"
"Teletubbies say Eh-oh"