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

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

    SHORTEST 3 solutions, 1 and 2 handle cases when s string is "", null and undefined:

     s&&s[0].toUpperCase()+s.slice(1)        // 32 char
    
     s&&s.replace(/./,s[0].toUpperCase())    // 36 char - using regexp
    
    'foo'.replace(/./,x=>x.toUpperCase())    // 31 char - direct on string, ES6
    

    let s='foo bar';
    
    console.log( s&&s[0].toUpperCase()+s.slice(1) );
    
    console.log( s&&s.replace(/./,s[0].toUpperCase()) );
    
    console.log( 'foo bar'.replace(/./,x=>x.toUpperCase()) );

提交回复
热议问题