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

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

    If you're already (or considering) using lodash, the solution is easy:

    _.upperFirst('fred');
    // => 'Fred'
    
    _.upperFirst('FRED');
    // => 'FRED'
    
    _.capitalize('fred') //=> 'Fred'
    

    See their docs: https://lodash.com/docs#capitalize

    _.camelCase('Foo Bar'); //=> 'fooBar'

    https://lodash.com/docs/4.15.0#camelCase

    _.lowerFirst('Fred');
    // => 'fred'
    
    _.lowerFirst('FRED');
    // => 'fRED'
    
    _.snakeCase('Foo Bar');
    // => 'foo_bar'
    

    Vanilla js for first upper case:

    function upperCaseFirst(str){
        return str.charAt(0).toUpperCase() + str.substring(1);
    }
    

提交回复
热议问题