挑战:将字符串转换为脊柱大小写。脊柱小写字母是全小写字母连字符
function spinalCase(str) {
var res = str.replace(/\s/g, "-")
var result = res.replace(/_/g, '').toLowerCase();
return result;
}
仅当字符串之间有空格或没有下划线时,代码才有效。我一直在努力通过其余的测试用例,其他人有什么建议或想法吗?
spinalCase("This Is Spinal Tap") should return "this-is-spinal-tap".
spinalCase("thisIsSpinalTap") should return "this-is-spinal-tap".
spinalCase("The_Andy_Griffith_Show") should return "the-andy-griffith-show".
spinalCase("Teletubbies say Eh-oh") should return "teletubbies-say-eh-oh".
spinalCase("AllThe-small Things") should return "all-the-small-things".
答案 0 :(得分:1)
您可以删除字符串开头/结尾的所有非字母数字字符,将这些连续的字符替换为-
,然后在小写字母和大写字母之间插入连字符,然后将全部小写。
function spinalCase(str) {
return str.replace(/^[\W_]+|[\W_]+$|([\W_]+)/g, function ($0, $1) {
return $1 ? "-" : "";
}).replace(/([a-z])(?=[A-Z])/g, '$1-').toLowerCase();
}
console.log(spinalCase("This Is Spinal Tap")); // "this-is-spinal-tap".
console.log(spinalCase("thisIsSpinalTap")); // "this-is-spinal-tap".
console.log(spinalCase("The_Andy_Griffith_Show")); // "the-andy-griffith-show".
console.log(spinalCase("Teletubbies say Eh-oh")); //"teletubbies-say-eh-oh".
console.log(spinalCase("AllThe-small Things")); // "all-the-small-things".
详细信息
.replace(/^[\W_]+|[\W_]+$|([\W_]+)/g, function ($0, $1) { return $1 ? "-" : ""; })
-删除字符串开头(^[\W_]+
)/末尾([\W_]+$
)的所有非字母数字字符,将这些连续的字符替换为-
(([\W_]+)
).replace(/([a-z])(?=[A-Z])/g, '$1-')
-在大小写字母之间插入连字符。答案 1 :(得分:0)
此question version的答案:当输入字符串使用camel-case时,我们就不需要字典,而只能使用正则表达式:
let s="exampleStringTwoThe-smallThing";
let r=s.replace(/([A-Z][a-z\-]*)/g, ' $1');
console.log(r);
对于当前问题版本:
s.replace(/( |_)+/g,'-').replace(/([a-z])(?=[A-Z])/g, '$1-').toLowerCase()
function spinalCase(s) {
return s.replace(/( |_)+/g,'-').replace(/([a-z])(?=[A-Z])/g, '$1-').toLowerCase();
}
console.log( spinalCase("This Is Spinal Tap") ) // should return "this-is-spinal-tap".
console.log( spinalCase("thisIsSpinalTap") ) // should return "this-is-spinal-tap".
console.log( spinalCase("The_Andy_Griffith_Show") ) // should return "the-andy-griffith-show".
console.log( spinalCase("Teletubbies say Eh-oh") ) // should return "teletubbies-say-eh-oh".
console.log( spinalCase("AllThe-small Things") ) // should return "all-the-small-things".
我通过使用Wiktor answer删除replace
来改善解决方案