Javascript 为字符串制作自定义正则表达式驼峰命名法解决方案时出现错误结果

Javascript wrong outcome when crafting a custom regex camelCase solution for strings

我正在尝试 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 不存在,它将 return undefined 这将导致您的条件始终 return false.

将行更改为:

function(letter, index) {
    return index === 0 && letter === letter.toLowerCase()  ? 
        letter.toLowerCase() : letter.toUpperCase();
}

如何将其简化为:

function toCamelCase(str) {
    return str.replace(/[-_](.?)/g, function(match, p1) {
        return p1.toUpperCase();
    })
}

document.write(toCamelCase("the-stealth-warrior") + "<br>");


document.write(toCamelCase("The_Stealth_Warrior")  + "<br>");

解释:

[-_] 查找 -_

(.?) 后跟任何其他字符并将此其他字符放在一个组中。

然后使用自定义回调调用 .replace(),使用 g 标志进行所有匹配。

自定义回调将作为第一个参数传递完整匹配,并将匹配中的任何组作为后续参数传递。由于我们想要将其转换为只是第一组的大写版本,因此我们只需将第二个参数大写为 return p1.toUpperCase() ,然后将整个匹配替换为第一个匹配组的大写版本。然后将 _x 转换为 X.

这会跳过前导字符,因为它前面没有 -_

这将跳过任何尾随 -_,因为它后面没有字符。