So i solved it after dealing with a strange bug with my first iteration. Essentially the first element appeared twice: once as an uppercase letter then as a lower case.
the following is my final code:
function titleCase(str) {
let finalStr = str.toUpperCase().charAt(0)
for (var i = 1, len = str.length; i < len ; i++){
if (str.charAt(i - 1) == " "){
finalStr += str.toUpperCase().charAt(i);
}
else
finalStr += str.toLowerCase().charAt(i);
}
return finalStr;
}
console.log(titleCase("I'm a little tea pot"));
next is my buggy code that i have no idea why it is bugging:
function titleCase(str) {
let finalStr = ""
for (var i = 0, len = str.length; i < len ; i++){
if (i == 0){
finalStr += str.toUpperCase().charAt(i);
}
if (str.charAt(i - 1) == " "){
finalStr += str.toUpperCase().charAt(i);
}
else
finalStr += str.toLowerCase().charAt(i);
}
return finalStr;
}
console.log(titleCase("I'm a little tea pot"));
So two questions:
-
Is this a suboptimal/not good code to solve a problem like this? The answer said that i should have split it into an Array and used replace. If it is bad code, why is this inferior to the provided solution?
-
Why did my buggy solution repeat the first character of the string twice?