It's not working because you still need to assign the result of strAr[i].charAt(0).toUpperCase()
:
strAr[i] = strAr[i].charAt(0).toUpperCase() + strAr[i].slice(1);
It's worth pointing out that the .toUpperCase()
/.toLowerCase()
methods do not mutate/alter the value of the string (which is why you need to assign it). You can simplify your code to the following:
Example Here
function titleCase(str) {
var strAr = str.toLowerCase().split(' ');
for (var i = 0; i < strAr.length; i++) {
strAr[i] = strAr[i].charAt(0).toUpperCase() + strAr[i].slice(1);
}
return strAr.join(' ');
}
console.log(titleCase('This is a simple test.'));
// This Is A Simple Test.
As an alternative to what you wrote, you could also use the following:
Example Here
function titleCase (str) {
return str.toLowerCase().replace(/(^|\s)(\w)/g, function(x) {
return x.toUpperCase();
});
}
console.log(titleCase('This is a simple test.'));
// This Is A Simple Test.
It will convert the entire input string to lower case, and then capitalize all characters succeeding whitespace (based on the match).