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

前端 未结 30 2272
南方客
南方客 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:32

    CSS only

    p::first-letter {
      text-transform: uppercase;
    }
    
    • Despite being called ::first-letter, it applies to the first character, i.e. in case of string %a, this selector would apply to % and as such a would not be capitalized.
    • In IE9+ or IE5.5+ it's supported in legacy notation with only one colon (:first-letter).

    ES2015 one-liner

    Since there are numerous answers, but none in ES2015 that would solve original problem efficiently, I came up with the following:

    const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1);
    

    Remarks

    • parameters => function is so called arrow function.
    • I went with name capitalizeFirstChar instead of capitalizeFirstLetter, because OP didn't asked for code that capitalizes the first letter in the entire string, but the very first char (if it's letter, of course).
    • const gives us the ability to declare capitalizeFirstChar as constant, which is desired since as a programmer you should always explicitly state your intentions.
    • In the benchmark I performed there was no significant difference between string.charAt(0) and string[0]. Note however, that string[0] would be undefined for empty string, so it should be rewritten to string && string[0], which is way too verbose, compared to the alternative.
    • string.substring(1) is faster than string.slice(1).

    Benchmark

    • 4,956,962 ops/s ±3.03% for this solution,
    • 4,577,946 ops/s ±1.2% for the most voted answer.
    • Created with JSBench.me on Google Chrome 57.

提交回复
热议问题