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

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

    For another case I need it to capitalize the first letter and lowercase the rest. The following cases made me change this function:

    //es5
    function capitalize(string) {
        return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
    }
    capitalize("alfredo")  // => "Alfredo"
    capitalize("Alejandro")// => "Alejandro
    capitalize("ALBERTO")  // => "Alberto"
    capitalize("ArMaNdO")  // => "Armando"
    
    // es6 using destructuring 
    const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();
    

提交回复
热议问题