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

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

    String.prototype.capitalize = function(allWords) {
       return (allWords) ? // if all words
          this.split(' ').map(word => word.capitalize()).join(' ') : //break down phrase to words then  recursive calls until capitalizing all words
          this.charAt(0).toUpperCase() + this.slice(1); // if allWords is undefined , capitalize only the first word , mean the first char of the whole string
    }
    

    And then:

     "capitalize just the first word".capitalize(); ==> "Capitalize just the first word"
     "capitalize all words".capitalize(true); ==> "Capitalize All Words"
    

    Update Nov.2016 (ES6), just for FUN :

    const capitalize = (string = '') => [...string].map(    //convert to array with each item is a char of string by using spread operator (...)
        (char, index) => index ? char : char.toUpperCase()  // index true means not equal 0 , so (!index) is the first char which is capitalized by `toUpperCase()` method
     ).join('')                                             //return back to string
    

    then capitalize("hello") // Hello

提交回复
热议问题