lowerCamelCase,忽略字符串的第一个字母

lowerCamelCase, ignoring the first letter of string

尝试创建一个函数,如果为真,则 returns UpperCamelCase 传递,如果为假,则 lowerCamelCase

到目前为止我的第一点没问题,但不知道如何忽略字符串的第一个字母。我用过 charAt[0] 但 returns 只是第一个字符。

我看过 these threads 但不知道如何操作。

到目前为止,这是我的代码:

function sentenceToCamelCase(str, bool) {
  if (bool) {
    return str
      .toLowerCase()
      .split(" ")
      .map(w => w[0].toUpperCase() + w.substr(1))
      .join("");
  } else {
    return str
      .toLowerCase()
      .split(" ")
      .map(w => w[0].toUpperCase() + w.substr(1))
      .join("");
  }
}

我收到这个错误:

AssertionError: expected 'ThisSentence' to deeply equal 'thisSentence'

刚接触 JS,谁能帮帮我?谢谢。

如果 bool 参数仅应将输出的第一个字符更改为小写或大写,您可以使用以下解决方案。如果这不是您想要的,请在评论中告诉我。

function sentenceToCamelCase(str, bool) {
  let res = str
      .toLowerCase()
      .split(" ")
      .map(w => w[0].toUpperCase() + w.substr(1))
      .join("");
  if(bool) {
    return res[0].toUpperCase() + res.substr(1);
  }
  else {
    return res[0].toLowerCase() + res.substr(1);
  }
}

console.log(sentenceToCamelCase("this sentence", true));
console.log(sentenceToCamelCase("this sentence", false));

你可以只搜索space和一个字符,然后根据布尔值替换。

function sentenceToCamelCase(str, bool) {
    var i = +bool;
    return str.replace(/(^|\s+)(.)/g, (_, __, s) => i++ ? s.toUpperCase(): s);
}

console.log(sentenceToCamelCase('once upon a time', true));
console.log(sentenceToCamelCase('once upon a time', false));