String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
};
function titleCase(str) {
var newTitle = str.split('');
var updatedTitle = [];
for (var st in newTitle) {
updatedTitle[st] = newTitle[st].toLowerCase().replaceAt(0, newTitle[st].charAt(0).toUpperCase());
}
return updatedTitle.join(' ');
}
titleCase("I'm a little tea pot");
/* var newTitle = str.split(' ');
var updatedTitle = [];
for (var st in newTitle) {
updatedTitle[st] = newTitle[st].toLowerCase().replaceAt(0, newTitle[st].charAt(0).toUpperCase());
}
return updatedTitle.join(' ');
} */
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36.
This line here is splitting the input string into individual characters. This means your loop is replacing every single letter instead of the first letter of each word. You will want to split on the space character str.split(' ') instead of empty string.
Another note while we’re here, it is generally not a good idea to extend the prototype of a built-in class like String with your own methods, but for a challenge like this it’s not a big deal.
it is generally not a good idea to extend the prototype of a built-in class like String with your own methods
This would seem a good intro to the Cardinal Rule of SW Development:
Maximize cohesion; minimize coupling
Many design patterns are simply examples of how to avoid naively or carelessly violating this rule.
The reason why one doesn’t extend the prototype of a built-in class like String is because it introduces a global coupling to every usage of the string type throughout the entire scope of the application.