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

标签 javascript regex string replace ternary-operator

我正在尝试进行 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/

相关文章:

javascript - Sequelize 获取重复条目 : 'ER_DUP_ENTRY'

javascript - struts2 optiontransferselect 从数据库中检索和显示值

Go中的正则表达式字符串

c++ - 初始化 QString 的最佳方法

c - 如何从 C 中函数返回的指针访问字符串

Javascript 函数在以面向对象的方式定义时可以工作,但通常不能工作

javascript - 登录网站失败

regex - 难以构建适当的正则表达式来捕获字符串

c# - .Net 简单正则表达式二次复杂度

c++ - 如何转换 int 变量并附加到 const wchar_t*