function titleCase(str) {
var words = str.split(" ");
for (var i = 0; i < words.length; i++) {
words[i][0].toUpperCase();
}
words = words.join(" ");
return words;
}
titleCase("I'm a little tea pot");
You need to concatenate the rest of the lowercase letters to the same words[i]
function titleCase(str) {
var words = str.toLowerCase().split(" ");
for (var i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1, words[i].length);
console.log(words);
}
return words.join(" ");
}
It was working in your code before… but you’re not assigning the results to anything. So at the end of your for…loop, nothing was changed in your words array. It still contains the original str.
In the corrected code, you see it being assigned back to words[i].
PLUS… this is just the first letter of the word. You forgot to add the rest of the word.
The
+ words[i].substr(1, words[i].length)
takes care of adding the rest of word.
PLUS… you didn’t take into account the condition of “what if a letter in the middle of the word, or the rest of the words are uppercase?”
so to take account of these conditions, it’s better to lowercase everything first, before you work on capitalizing the start of each word.