题目
算法中级:短线连接格式
在这道题目中,我们需要写一个函数,把一个字符串转换为“短线连接格式”。短线连接格式的意思是,所有字母都是小写,且用-连接。比如,对于Hello World,应该转换为hello-world;对于I love_Javascript-VeryMuch,应该转换为i-love-javascript-very-much。
spinalCase(“This Is Spinal Tap”)应该返回"this-is-spinal-tap"。
spinalCase(“thisIsSpinalTap”)应该返回"this-is-spinal-tap"。
spinalCase(“The_Andy_Griffith_Show”)应该返回"the-andy-griffith-show"。
spinalCase(“Teletubbies say Eh-oh”)应该返回"teletubbies-say-eh-oh"。
spinalCase(“AllThe-small Things”)应该返回"all-the-small-things"。
解题
function spinalCase(str) {
let CharReg = /\s|-|_/g;
//字符串的所有空格 - _字符 替换为-
let clearCharStr = str.replace(CharReg,'-');
let spaceStr = '',
reg = /[A-Z]/;
for(let i = 0,len =str.length;i < len;i++){
let current = clearCharStr[i],
next =clearCharStr[i-1];
if(next){
// 如果当前字符为写大小字母, 且它的上一个字符不为特殊字符-, 则将当前字符加上-字符
if(reg.test(current) && !(/-/g.test(next)) ){
clearCharStr = clearCharStr.replace(current,`-${
current}`)
}
}
}
let newStr = clearCharStr.toLocaleLowerCase(),
arrStr = newStr.split(/-/);
return arrStr.join('-')
// return str;
}
spinalCase('This Is Spinal Tap');