freeCodeCamp: Title Case a Sentence

Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.

For the purpose of this exercise, you should also capitalize connecting words like “the” and “of”.

Remember to use Read-Search-Ask if you get stuck. Write your own code.

Here are some helpful links:

Starting Code:

function titleCase(str) {
return str;
}
titleCase("I'm a little tea pot");

Use Cases:

titleCase("I'm a little tea pot") should return a string.
titleCase("I'm a little tea pot") should return "I'm A Little Tea Pot".
titleCase("sHoRt AnD sToUt") should return "Short And Stout".
titleCase("HERE IS MY HANDLE HERE IS MY SPOUT") should return "Here Is My Handle Here Is My Spout".

Solution:

function titleCase(str) {
var words = str.toLowerCase().split(' ');
var sentence = '';
words.forEach(function(word){
sentence += word.substring(0,1).toUpperCase() + word.substring(1,word.length) + ' ';
});
sentence = sentence.substring(0, sentence.length-1);
return sentence;
}