I am trying to capitalize the first letter of every word in the string. I wanted to do it in 3 steps:
- Turn string into an array using .split().
- Create a loop and change the first letter in every word by addressing it with an array index.
- Finally I wanted to use .join to put everything back in a string.
But something went wrong and I can't go to the 3rd step. The for loop does change the letter to uppercase, but when I return the variable cap it only returns the first capitalized letter of the last word in the string. In the example it's P(the last word is pot), if I erase pot it returns T(because tea becomes the last word).
Why doesn't the cap variable return the whole array with capitalized first letters? What am I missing?
Here's the code:
function titleCase(str) {
var arr = str.split(" ");
for (i = 0; i < arr.length; i++) {
var cap = arr[i][0].toUpperCase();
}
return cap;
}
titleCase("I'm a little tea pot");