I’m trying to solve this really basic algorithm to convert a string into a title case string.
The method I used was:
- Convert the string into lowercase using .toLowerCase();
- then split the string into individual words using .split(’ ');
- then use a for loop to run and select the first character of the array[i] and turn it into uppercase using .toUpperCase()
- then adding that to str.slice(1); to add the rest of the word
- then using the .join(’ ') method to put it back together into a string
This is the code I wrote that won’t work, and I’d like to know why as I think my logic seems sound. I know I’m creating too many variables but I think the code should still work…
function titleCase(str) {
var lowerCaseSplit = str.toLowerCase().split(" ");
for(var i=0 ; i < lowerCaseSplit.length ; i++) {
var upperCaseStr = lowerCaseSplit[i].charAt(0).toUpperCase() + lowerCaseSplit[i].slice(1);
}
var finalJoin = upperCaseStr.join(' ');
return finalJoin;
}
With the above code, I get the following error:
uncaught TypeError: upperCaseStr.join is not a function.
Now I know this is the code that does work, and I’d like to know what I’m doing wrong, or why my approach is wrong:
function titleCase(str) {
str = str.toLowerCase().split(' ');
for(var i=0 ; i < str.length ; i++){
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
}
return str.join(' ');
}