arr
is an array of strings, but strings are immutable - simply calling toUpperCase()
on a character will just give you a reference to a new, uppercase character, without changing the original string. You need to explicitly reassign the array item:
function titleCase(str) {
let arr = str.toLowerCase().split(" ");
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
return arr.join(" ");
}
console.log(titleCase("I'm a little tea pot"));
Or, perhaps more elegantly, you could use a regular expression. The following uses lookbehind, which works in recent versions of Chrome, Opera, and Node; lookbehind makes for cleaner-looking code, but it's not supported everywhere:
const titleCase = str => str.replace(
/(?<=^|\s)\S/g,
firstChar => firstChar.toUpperCase()
);
console.log(titleCase("I'm a little tea pot"));
Or, without lookbehind:
const titleCase = str => str.replace(
/(\S)(\S*)/g,
(_, firstChar, rest) => firstChar.toUpperCase() + rest
);
console.log(titleCase("I'm a little tea pot"));