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\"
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"
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