Can any one please tell me what is the problem with this code. I hand run it and i think it works fine, obviously there is some problem please help anyone
Your code so far
function titleCase(str) {
//1. Method1: Convert str to arr.
//2. Use given str and else if to find space.
let foundSpace =false;
for(let i=0;i<str.length;i++){
if(str[i]!==" " && !foundSpace){
i==0?str[i].toUpperCase():str[i].toLowerCase();
}
else if(str[i]!==" " && foundSpace){
str[i].toUpperCase();
foundSpace = false;
}else if(str[i]==" "){
foundSpace = true;
}
}
return str;
}
console.log(titleCase("I'm a little tea pot"));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36.
this is not doing anything
string are immutable, you can’t change a single character in the string just like that and toUpperCase returns a new value, doesn’t change what is applied to
it doesn’t work, you are logging to the console the return value of str[0].toUpperCase(), but it doesn’t change the value of str
try this and see if it changes anything
because toUpperCase return a new value, doesn’t change the value of what it is applied on, and you are still trying to change a character in the string, you can’t change pieces of the string
if you try to do it manually it errors:
let str = "hello";
str[0] = "H"; // error, impossible to do
you are trying to do the same thing in a fancier way but it is still not possible
and this just doesn’t work:
let str = "hello";
str.charAt(0).toUpperCase();
console.log(str);
make the above work and you can solve the algorirhm
let str1 = "I'm a little tea pot";
str1 = str1.toLowerCase().concat(" tHIS IS ");
console.log(str1);
//i'm a little tea pot tHIS IS
I understand i cannot change a character within string, but when i change whole string to a lowerCase and doing concat and saving the value in same string variable str1. It works
Since it is immutable it should not change, what exactly is happening ? is it creating new reference to str1??
Actually i am also confused if I declate str1 as const the above code will not work, so what exactly is happening behind the scene ?
you can change a whole string alright in that way
you can do str1 = str1.toLowerCase(), but as toLowerCase() return a new value for the code it is the same as doing str1 = "A wizard went to the market to buy an apple"
you can’t still do str1[1] = str1[1].toLowerCase()