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

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

    String.prototype.capitalize = function(){
        return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase();
        } );
    };
    

    Usage:

    capitalizedString = someString.capitalize();
    

    This is a text string => This Is A Text String

提交回复
热议问题