I'm learning how to capitalize the first letter of each word in a string and for this solution I understand everything except the word.substr(1) portion. I see that it's adding the broken string but how does the (1) work?
function toUpper(str) { return str .toLowerCase() .split(' ') .map(function(word) { return word[0].toUpperCase() + word.substr(1); }) .join(' '); } console.log(toUpper("hello friend"))
In JavaScript, we have a method called toUpperCase() , which we can call on strings, or words. As we can imply from the name, you call it on a string/word, and it is going to return the same thing but as an uppercase. For instance: const publication = "freeCodeCamp"; publication[0].
To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.
To capitalize the first letter of a string in React: Use the charAt() method to get the first letter of the string. Call the toUpperCase() method on the letter. Use the slice() method to get the rest of the string. Concatenate the results.
In JavaScript capitalize first letter using charAt (), slice () or toUpperCase () methods. These JavaScript methods can capitalize the first letter of a JavaScript string or the first letter of each word in a JS string. In this review, you will master first letter capitalization in JS with the above methods.
This capitalizes the first letter of only the 1st word of the string. The OP is asking about capitalizing each word! This routine will handle hyphenated words and words with apostrophe.
Use the built-in method toUpperCase () on the letter you want to transform to uppercase. The next step is to take a sentence and capitalize every word from that sentence.
Now that we know how to access a letter from a word, let's capitalize it. In JavaScript, we have a method called toUpperCase (), which we can call on strings, or words. As we can imply from the name, you call it on a string/word, and it is going to return the same thing but as an uppercase.
The return value contain 2 parts:
return word[0].toUpperCase() + word.substr(1);
1) word[0].toUpperCase()
: It's the first capital letter
2) word.substr(1)
the whole remain word except the first letter which has been capitalized. This is document for how substr works.
Refer below result if you want to debug:
function toUpper(str) { return str .toLowerCase() .split(' ') .map(function(word) { console.log("First capital letter: "+word[0]); console.log("remain letters: "+ word.substr(1)); return word[0].toUpperCase() + word.substr(1); }) .join(' '); } console.log(toUpper("hello friend"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With