我正在尝试进行 Javascript 挑战,其说明是:
Complete the method/function so that it converts dash/underscore delimited
words into camel casing. The first word within the output should be
capitalized only if the original word was capitalized.
Examples:
toCamelCase("the-stealth-warrior")
// returns "theStealthWarrior"
toCamelCase("The_Stealth_Warrior")
// returns "TheStealthWarrior"
我的解决方案是:
function toCamelCase(str) {
console.log(str);
var camel = str.replace(/(?:^\w|[A-Z]|-\w|_\w)/g, function(letter, index) {
return index === 0 && letter === letter.toLowercase ?
letter.toLowercase : letter.toUpperCase();
}).replace(/(-|_)/g, "");
console.log(camel);
return camel;
}
将我的代码与测试用例一起使用时的输出是:
toCamelCase('the_stealth_warrior') did not return correct value -
Expected: theStealthWarrior, instead got: TheStealthWarrior
有什么想法哪里出了问题吗?我觉得三元运算符中的条件应该返回小写 t。
最佳答案
这里的这段代码导致了您的问题:
function(letter, index) {
return index === 0 && letter === letter.toLowercase ?
letter.toLowercase : letter.toUpperCase();
}
您可能打算使用 toLowerCase()
,但您却提供了对 letter
不存在的属性的引用。由于 toLowercase
不存在,它将返回 undefined
这将导致您的条件始终返回 false。
将行更改为:
function(letter, index) {
return index === 0 && letter === letter.toLowerCase() ?
letter.toLowerCase() : letter.toUpperCase();
}
关于为字符串制作自定义正则表达式驼峰式解决方案时,Javascript 出现错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32061084/