Hi,
I’m attempting to solve this problem. I came up with the following solution
function titleCase(str) {
let strArr = str.split(" "), finStr = [];
for(let i = 0; i < strArr.length; i++) {
for(let j = 0; j < strArr[i].length; j++) {
if (j === 0) {
finStr.push(strArr[i][j].toUpperCase());
} else {
finStr.push(strArr[i][j].toLowerCase());
}
}
finStr.push(" ");
}
return finStr.join("");
}
console.log(titleCase("I'm a little tea pot"));
console.log(titleCase("sHoRt AnD sToUt"));
console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"))
It returns what I need, but it fails to solve all the test cases from freeCodeCamp.
What do the failing tests say?
I get these messages
// running tests
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.
// tests completed
// console output
You are adding an extra space to the end of all of your strings.
1 Like
I see now. Thanks for your help!
One more question… Does my code make sense? How can I improve it?
If you haven’t already made this change to your code, I suggest removing the finStr.push(" ") entirely and changing your finStr.join("") to finStr.join(" ") this will add spaces between your words only.
2 Likes
I used the trim method, but your version makes much more sense.
I’m glad I could help. Happy coding!