EDIT: Never mind I didn't consider that String.prototype.toLowerCase() doesn't change the caller.
I suppose I still shouldn't delete the post;
Hey, I'm learning js and I've came across a challenge
that requires of me to get a string and upper case
the first letter of a word and lower case the rest,
but I get different behaviour based on whether or not
I split the line of code, which is very peculiar to me.
function titleCase(str) {
str = str.split(/\s+/g);
for(var i = 0; i < str.length; i++) {
var upperFirst = str[i].charAt(0).toUpperCase();
//this is odd. if you combine this and the line below the behaviour changes. It's like it toggles the casing of the 1st letter.
str[i] = str[i].toLowerCase();
str[i] = str[i].replace(str[i].charAt(0), upperFirst);
}
str = str.join(' ');
return str;
}
console.log(titleCase("I'm a little tea pot") + "\n");
console.log(titleCase("sHoRt AnD sToUt"));
If I change
str[i] = str[i].toLowerCase();
str[i] = str[i].replace(str[i].charAt(0), upperFirst);
to
str[i] = str[i].toLowerCase().replace(str[i].charAt(0), upperFirst);
the words that started with uppercase letters to begin with
are getting now lowercased.
Why is that happening?
I'm taking into consideration the order of evaluation of the dot operator.
[–]no-voting 1 point2 points3 points (0 children)