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"))
Top comments (7)
If you check the prototype of
substr
(see the MDN documentation), you can see that there is this second optional parameterlength
:And the documentation states that
So when you call
word.substr(1)
, this is the equivalent of:word.substr(1)
is creating a new string fromword
starting on the character at index1
. So it's basically the whole word except the first character.Example:
If you are trying to find an effective way to do this and your app uses CSS for a front-end, you can use text-transform: capitalize; to do it.
But if it is just for a JavaScript-only app or practice, the other comments will be more helpful.
i think you should use slice instead of substr
Well, try to regex: (good site to practice is regex101.com/)
Now, some funny but not recommendend for this case alone:
Perhaps consider looking at regex and groupings. With regex you can target each single letter that falls after a whitespace, you can do this via the String replace() function. Then there is no need to split iterate and join.
developer.mozilla.org/en-US/docs/W...
Regex is indeed powerful, but I wouldn't recommend a beginner try to learn it.