My challenge is to capitalize the first letter of each word in a string while making sure all the other letters are lowercase. I have spent more hours then I'm willing to admit on this and my code is shown below. It's about 95% complete.
It's only flaw is that it returns contractions like "I'm" as "I'M". For some reason it sees contractions as two separate words. I tested this my putting a console.log immediately after the step that capitalizes the first letter (I have commented it out in the example). it returns that it is capitalizing both "I" and "M" in the same step. How do I get get it change only the "I"?
function titleCase(str) {
str = str.toLowerCase(); //make everything lowercase
str = str.split(" "); //make the string to array
for(i = 0; i < str.length; i++){
var strItem = str[i]; //take item in array
strItem = strItem.replace(/\b./g, function(m){ return m.toUpperCase(); }); //capitalize it
//console.log(strItem);
str[i] = strItem; //put changed item back into array
}
str = str.join(" "); //turn array back into string
return str;
}
titleCase("I'm a little tea pot");
Thank you for your time.