One of the challenges I'm facing right now is how to properly capitalize the first letter of each word in a string while keeping all other letters in lowercase. Although I've dedicated countless hours to working on this, my code appears to be about 95% complete.
The only issue that remains is that when it comes across contractions like "I'm", it capitalizes both parts as separate words ("I" and "M") rather than just the "I". I even added a console.log to check what's happening, and it confirms that both letters are being capitalized in the same step. How can I ensure that only the initial letter is transformed?
function titleCase(str) {
str = str.toLowerCase(); //convert everything to lowercase
str = str.split(" "); //split the string into an array
for(i = 0; i < str.length; i++){
var strItem = str[i]; //retrieve item from array
strItem = strItem.replace(/\b./g, function(m){ return m.toUpperCase(); }); //capitalize the first letter
//console.log(strItem);
str[i] = strItem; //update item in the array
}
str = str.join(" "); //merge array elements back into a string
return str;
}
titleCase("I'm a little tea pot");
I appreciate your assistance with this matter.