How come the code below does not work?
function titleCase(str) {
str = str.toLowerCase().split(' ');
for (var x = 0; str[x]; x++) {
str[x][0] = str[x][0].toUpperCase();
}
return str;
}
titleCase("heya brother how are you?");
How come the code below does not work?
function titleCase(str) {
str = str.toLowerCase().split(' ');
for (var x = 0; str[x]; x++) {
str[x][0] = str[x][0].toUpperCase();
}
return str;
}
titleCase("heya brother how are you?");
See my comments about your existing code below:
function titleCase(str) {
str = str.toLowerCase().split(' ');
for (var x = 0; str[x]; x++) {
str[x][0] = str[x][0].toUpperCase();
// strings are immutable in JavaScript. You are trying to replace a specific
// character in one of the words directly, but instead you need to reassign a new
// word which is the capitalization of the current word in the array iteration.
// In pseudocode this would be str[x] = firstLetterofWord + restOfWord
// Now you just need to figure out how to create firstLetterofWord and restOfWord
}
console.log(str) // displays [ 'heya', 'brother', 'how', 'are', 'you?' ]
return str; // need to join the array back together before returning it
}
titleCase("heya brother how are you?");
Thanks so much, Randell. That makes perfect sense.