【问题标题】:Make first letter of array statement uppercase in JS在JS中将数组语句的第一个字母大写
【发布时间】:2020-08-06 21:59:21
【问题描述】:

我有一个数组,我想使用 map 将第一个字母转换为大写字母

const arrayTOCapital = [
  'hi world',
  'i want help ',
  'change first letter to capital',

 ];

const arrayFirstLetterToCapital = () => {
  return arrayTOCapital.map(function(x){ return 
      x.charAt(0).toUpperCase()+x.slice(1) })
}

输出应该是:

Hi World
I Want Help
Change First Letter To Capital

【问题讨论】:

    标签: javascript uppercase


    【解决方案1】:

    您可以只使用正则表达式/\b\w/g 来查找以单词边界(例如空格)开头的所有字母并将其替换为大写版本

    const arrayTOCapital = [
      'hi world',
      'i want help ',
      'change first letter to capital',
    ];
    
    console.log(arrayTOCapital.map(x => x.replace(/\b\w/g, c => c.toUpperCase())));

    【讨论】:

    • 这个字母/\b\w/g的单词是什么?
    • 他在上面解释了它们,除了 g 用于全局搜索和 w 是单词字符。
    【解决方案2】:

    您需要对句子中的每个单词应用相同的逻辑,然后join它们如下:

    const arrayTOCapital = [
      'hi world',
      'i want help ',
      'change first letter to capital',
    
    ];
    
    const arrayFirstLetterToCapital = () => { 
         return arrayTOCapital.map(function(x){ 
              return x.split(" ").map(function(y){
                   return y.charAt(0).toUpperCase()+y.slice(1);
              }).join(" ");
         });
    }
    
    console.log(arrayFirstLetterToCapital());

    【讨论】:

      【解决方案3】:

      const arrayTOCapital = [
        'hi world',
        'i want help',
        'change first letter to capital'
       ];
       
       const results = arrayTOCapital.map(
         str => str.split(' ').map(s => s[0].toUpperCase() + s.substr(1)).join(' ')
       )
       
       console.log(results);

      如果你想写一个句子,你可以在最后一个括号后添加一个额外的 .join(' ')。

      【讨论】:

        猜你喜欢
        • 2012-06-23
        • 1970-01-01
        • 2019-05-05
        • 1970-01-01
        • 1970-01-01
        • 2011-07-20
        • 2018-07-08
        • 2014-05-13
        • 2013-08-13
        相关资源
        最近更新 更多