【问题标题】:lowerCamelCase, ignoring the first letter of stringlowerCamelCase,忽略字符串的第一个字母
【发布时间】:2018-04-08 16:07:48
【问题描述】:

尝试创建一个函数,如果传递 true,则返回 UpperCamelCase,如果传递 false,则返回 lowerCamelCase

到目前为止,我的第一个字母还不错,但不知道如何忽略字符串的第一个字母。我使用了charAt[0],但它只返回第一个字符。

我见过thesethreads,但不知道怎么做。

这是我目前的代码:

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: 预期 'ThisSentence' 与 'thisSentence' 完全相等

对 JS 很陌生,谁能帮帮我?谢谢。

【问题讨论】:

    标签: javascript string camelcasing


    【解决方案1】:

    如果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));

    【讨论】:

    • 感谢您的帮助。使用您的解决方案,它没有通过我的第一个测试,当 ("this sentence", true) 被传递时,它应该返回 'ThisSentence'。该函数有两个参数;句子和布尔值,如果要返回 UpperCamelCase,则为 true,如果要返回 lowerCamelCase,则为 false
    • @VisualXZ 我已经更新了方法。它现在通过你的测试了吗?
    【解决方案2】:

    你可以只搜索空格和一个字符并根据布尔值替换。

    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));

    【讨论】:

      猜你喜欢
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 2014-06-05
      相关资源
      最近更新 更多