【发布时间】:2018-05-27 22:21:00
【问题描述】:
函数应该接受一个字符串作为参数,并采用驼峰式大小写。我在使用 regex 和 string.replace() 方法时遇到连字符问题。
camelCase('state-of-the-art') 应该返回 'state-of-the-art' camelCase("别担心 kyoko") 应该返回 "dontWorryKyoko"
以下内容适用于这两种情况,但我想让它干燥,去掉连字符 if 子句并将连字符大小写包含在 .replace() 中,它是回调。
function camelCase(phrase) {
let re = /[a-z]+/i;
let hyphens = /[-+]/g
if(typeof phrase !== 'string' || !phrase.match(re) || !phrase || phrase === null){
return "Please enter a valid string.";
} else if (phrase.match(hyphens)){
return phrase.toLocaleLowerCase();
}else{
return phrase.replace(/(?:^\w+|[A-Z]|\s+\w)/g, function(letter, index) {
return index == 0 ? letter.toLowerCase() : letter.toUpperCase();
}).replace(/\W+/g, '');
}
}
console.log(camelCase('state-of-the-art')) // 'state-of-the-art'
console.log(camelCase("Don't look back")) // dontLookBack
我们可以在没有连字符 if 子句的情况下使连字符的情况起作用吗?
另外我觉得camelCase("don't lOOk_BaCK") 应该是索引> 0 的小写字母,但它似乎并没有在控制台中这样做。
有人想帮忙吗?谢谢
【问题讨论】:
-
this 应该可以帮助您入门(我还没有尝试过)。
标签: javascript regex