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

前端 未结 30 3145
南方客
南方客 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's a more object-oriented approach:

    String.prototype.capitalize = function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
    }
    

    You'd call the function, like this:

    "hello world".capitalize();
    

    With the expected output being:

    "Hello world" 
    

提交回复
热议问题