I’m rather stuck on this particular challenge. I have indeed read some of the solutions provided by others but I’m curious as to why I can’t get this iteration loop method to work. Also I’m not interested in just copying and pasting code from others just to pass the challenge as that’s really not the idea.
Code should be fairly self explanatory, it just splits the input string and stores it in a new variable, then a separate new variable is made which will slowly have the altered parts of the string added to it as array elements. Finally the join function puts it all back together as a string and returns it.
The alterations to the elements of the split string are just done with for loops iterating over them. However the challenge just will not accept this code and I have no idea why.
Thank you
function titleCase(str) {
const tempStr = str.split(" ");
const newStr = [];
for (let i = 0; i < tempStr.length; i++)
{
tempStr[i][0].toUpperCase();
for (let j = 1; j < tempStr[i].length; j++)
{
tempStr[i][j].toLowerCase();
}
newStr[i] = tempStr[i];
}
return newStr.join(" ");
}
titleCase("I'm a little tea pot");
string is not mutable
since you have split the string into smaller string
you cant modify it to upperCase directly
you should assign a new variable to store tempStr[i][0].toUpperCase(); value
and you dont have to loop over over to convert all character to lower string individually
Oh my that’s a lot of replies very quickly. I didn’t expect that. I have some reading to do! I’ll get on it and then later today I’ll report back, thanks
function titleCase(str) {
const tempStr = str.split(" ");
const newStr = [];
for (let i = 0; i < tempStr.length; i++)
{
newStr[i] = tempStr[i][0].toUpperCase() + tempStr[i].slice(1).toLowerCase();
console.log(newStr[i]);
}
return newStr.join(" ");
}
titleCase("I'm a little tea pot");
And it works! I had a bit of trouble with the lowercase part but when I re-read some of the solutions offered by others I realised I could use the slice function followed by a toLowerCase function and that fixed that. Your replies have been very helpful, I didn’t realise at all that I was not doing anything with the return values from the toUpper and toLower functions. Thanks