How do I make the first letter of a string uppercase in JavaScript?

前端 未结 30 2215
南方客
南方客 2020-11-21 05:00

How do I make the first letter of a string uppercase, but not change the case of any of the other letters?

For example:

  • \"this is a test\"
30条回答
  •  鱼传尺愫
    2020-11-21 05:16

    If you're interested in the performance of a few different methods posted:

    Here are the fastest methods based on this jsperf test (ordered from fastest to slowest).

    As you can see, the first two methods are essentially comparable in terms of performance, whereas altering the String.prototype is by far the slowest in terms of performance.

    // 10,889,187 operations/sec
    function capitalizeFirstLetter(string) {
        return string[0].toUpperCase() + string.slice(1);
    }
    
    // 10,875,535 operations/sec
    function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }
    
    // 4,632,536 operations/sec
    function capitalizeFirstLetter(string) {
        return string.replace(/^./, string[0].toUpperCase());
    }
    
    // 1,977,828 operations/sec
    String.prototype.capitalizeFirstLetter = function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
    }
    

提交回复
热议问题