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

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

    Here is a shortened version of the popular answer that gets the first letter by treating the string as an array:

    function capitalize(s)
    {
        return s[0].toUpperCase() + s.slice(1);
    }
    

    Update:

    According to the comments below this doesn't work in IE 7 or below.

    Update 2:

    To avoid undefined for empty strings (see @njzk2's comment below), you can check for an empty string:

    function capitalize(s)
    {
        return s && s[0].toUpperCase() + s.slice(1);
    }
    

提交回复
热议问题