首页 / 问答 / JavaScript(js)中如何实现将一个字符串的首字母大写呢?

JavaScript(js)中如何实现将一个字符串的首字母大写呢?

javascript js String 字符串 1.47K 次浏览
0

在JavaScript/js的前端开发中,如何实现将一个字符串的首字母大写,且不改变任何其他字母的大小写呢?

期望的实现效果如下:

"this is a test" → "This is a test"
"the Eiffel Tower" → "The Eiffel Tower"
"/index.html" → "/index.html"
回复 [×]
提交评论
请输入评论内容

4 个回答

  • 0

    以下是使用JavaScript(js)实现的四种不同字符串首字母大写的函数及性能对比:

    // 10,889,187 次/每秒
    function capitalizeFirstLetter(string) {
        return string[0].toUpperCase() + string.slice(1);
    }
    
    // 10,875,535 次/每秒
    function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }
    
    // 4,632,536 次/每秒
    function capitalizeFirstLetter(string) {
        return string.replace(/^./, string[0].toUpperCase());
    }
    
    // 1,977,828 次/每秒
    String.prototype.capitalizeFirstLetter = function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
    }
    
    Rector的个人主页

    Rector

    2021-11-08 回答

    • 0

      使用 toUpperCase()slice()封装的函数:

      function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
      }
      
      console.log(capitalizeFirstLetter('foo')); // 输出:Foo
      
      Rector的个人主页

      Rector

      2021-11-08 回答

      • 0

        下面是一种更面向对象的方法:

        Object.defineProperty(String.prototype, 'capitalize', {
          value: function() {
            return this.charAt(0).toUpperCase() + this.slice(1);
          },
          enumerable: false
        });
        

        调用示例:

        "hello, world!".capitalize(); // 输出:"Hello, world!"
        
        Rector的个人主页

        Rector

        2021-11-08 回答

        • 0

          除了使用JavaScript(js)外,还可用纯CSS的样式来实现字符串首字母大写的效果,如下:

          p:first-letter {
              text-transform:capitalize;
          }
          
          Rector的个人主页

          Rector

          2021-11-08 回答

          我来回答