Was doing the question on Basic Algorithm Scripting: Title Case a Sentence, and I am not sure where did I go wrong,
I am thinking that when selecting a character from a string thru x[0], it is impossible to assign new values through this.
Would like to know if my assumption is correct and if so how do I get around this? I’ve tried charAt(0) but it does not work.
function titleCase(str) {
let newstr = str.toLowerCase().split();
for(let x in newstr){
x.replace(x[0],x[0].toUpperCase());}
return newstr.join(" ");
}
titleCase("I'm a little tea pot");
thank you for replying, yes I realized that I was using the for…in loop wrongly, I used a for loop instead but when I console.log, I was not getting the first letter to capitalize.
function titleCase(str) {
let newstr = str.toLowerCase().split(" ");
for(let x=0;x<newstr.length;x++){
newstr[x].replace(newstr[x][0],newstr[x][0].toUpperCase());
}
return newstr.join(" ");
}
Is this because it is not possible to replace characters using the bracket notation - newstr[x][0]?
replace returns a new value, you are not doing anything with that value - your loop is just calculating a thing, and then doing nothing with that thing
ahh okay my understanding of replace is totally off. I previously did not understand that the values of original array/string will not be replaced. After creating a new empty array, I was able to push the new values into it. Hence solving the question.
Thank you! Your explanation really helped.