【问题标题】:Capitalize first letter of each word using reduce in Javascript在Javascript中使用reduce将每个单词的首字母大写
【发布时间】:2019-08-28 04:08:23
【问题描述】:

该函数应将字符串中每个单词的首字母大写,然后返回大写字符串。

--- 例子

capitalize('a short sentence') --> 'A Short Sentence'

capitalize('a lazy fox') --> 'A Lazy Fox'

我在不使用 reduce 的情况下让它工作,但我想在 reduce 方面做得更好,但我无法让它工作。

capitalize = str => {
  //V1
  return str
  .split(" ")
  .map(w => {
    return w.charAt(0).toUpperCase() + w.slice(1);
  })
  .join(" ");
};

我正在尝试减少:

capitalize = str => {
    let index = 0;
      const arr = str.split("");
      return arr.reduce((acc, curr, i) => {
        console.log(acc);
        if (acc === " ") {
          return curr.toUpperCase();
        }
        index = i;
      }, arr[index]);
    };

【问题讨论】:

  • 如果输入类似于 heLLo 怎么办?在这种情况下需要什么输出?
  • @CodeManiac 谢谢你的提问。我看了一下测试用例,没有一个有这样的例子,所以我想没关系

标签: javascript


【解决方案1】:

一种选择是将字符串视为字符数组,如果字符是数组中的第一个元素,或者前面的元素是空格,则将字符大写:

const capitalize = str => [...str].reduce(
  (s, c, i, a) => s + (i === 0 || a[i - 1] === ' ' ? c.toUpperCase() : c),
  ''
);

console.log(capitalize('a short sentence'));

【讨论】:

    【解决方案2】:

    如果你想在这里使用reduce,它可能是最简单的(类似于你最初所做的)迭代单词而不是字母,其中累加器是大写的字符串你正在创造的过程中。唯一棘手的部分是在插入更改的单词之前检查是否需要添加空格:

    const capitalize = str => {
      const arr = str.split(" ");
      return arr.reduce((acc, word) => (
        acc + (acc === '' ? '' : ' ') // add space before next word if necessary
        + word[0].toUpperCase() + word.slice(1))
      , '');
    };
        
        
    console.log(capitalize('a short sentence')) // --> 'A Short Sentence'
    console.log(capitalize('a lazy fox')) // --> 'A Lazy Fox'

    不过,这不是那么可读。我觉得.map / .join 看起来更好。

    【讨论】:

      【解决方案3】:

      function capitalize(string) {
        return string.split(' ').reduce((accumulatedString, currentWord) =>  
        accumulatedString.concat(currentWord[0].toUpperCase() + currentWord.slice(1)), []).join(' ')
      }
      
      console.log(capitalize('a lazy fox'))

      【讨论】:

        【解决方案4】:

        只使用 CSS:

        p {
          text-transform: capitalize;
        }
        <p>a short sentence</p>

        使用 JavaScript Array.prototype.reduce():

        const str = 'a lazy fox';
        const capitalize = str => str
          .split(' ')
          .reduce((a, c) => {
            const word = `${c.charAt(0).toUpperCase()}${c.slice(1)}`;
            return a ? `${a} ${word}` : word;
          }, '');
        
        console.log(capitalize(str));

        【讨论】:

        • 哈哈谢谢你。我知道我可以做到,但我想在 JS 方面做得更好,特别是 reduce()
        • 您的代码在每个句子的开头添加了一个空格
        【解决方案5】:

        检查这个:

        const a = 'a lazy fox';
        const b = 'a short sentence';
        const capitalizeAllWord  = str => str && str.split(" ")
              .reduce((acc, curr)=> [...acc, `${curr.charAt(0).toUpperCase()}${curr.slice(1)}`] ,[])
              .join(" ");
        
        console.log(capitalizeAllWord(a));
        console.log(capitalizeAllWord(b));

        【讨论】:

          【解决方案6】:

          试试这个代码。它会帮助你。

               const input = 'a short sentenc'
               output = input.substring(0, 1).toUpperCase() + input.substring(1);
               console.log(output)

          【讨论】:

            猜你喜欢
            • 2015-11-10
            • 2016-05-01
            • 2014-11-15
            • 1970-01-01
            • 2020-08-30
            • 2015-11-04
            • 2012-11-11
            • 2012-07-24
            • 1970-01-01
            相关资源
            最近更新 更多