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

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

    Here is a function called ucfirst() (short for "upper case first letter"):

    function ucfirst(str) {
        var firstLetter = str.substr(0, 1);
        return firstLetter.toUpperCase() + str.substr(1);
    }
    

    You can capitalise a string by calling ucfirst("some string") -- for example,

    ucfirst("this is a test") --> "This is a test"
    

    It works by splitting the string into two pieces. On the first line it pulls out firstLetter and then on the second line it capitalises firstLetter by calling firstLetter.toUpperCase() and joins it with the rest of the string, which is found by calling str.substr(1).

    You might think this would fail for an empty string, and indeed in a language like C you would have to cater for this. However in JavaScript, when you take a substring of an empty string, you just get an empty string back.

提交回复
热议问题