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

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

    We could get the first character with one of my favorite RegExp, looks like a cute smiley: /^./

    String.prototype.capitalize = function () {
      return this.replace(/^./, function (match) {
        return match.toUpperCase();
      });
    };
    

    And for all coffee-junkies:

    String::capitalize = ->
      @replace /^./, (match) ->
        match.toUpperCase()
    

    ...and for all guys who think that there's a better way of doing this, without extending native prototypes:

    var capitalize = function (input) {
      return input.replace(/^./, function (match) {
        return match.toUpperCase();
      });
    };
    

提交回复
热议问题