Question about converting a string into title case

Question about converting a string into title case
0

#1

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(' ');

}

#2

The reason that the first answer does not work is because each time the loop runs, upperCaseStr is being reassigned another string value, so when you try to use the .join() array method on a string, you get a Type Error.

In your working solution, you are reassigning right side string value to a place (index) in the existing str array, so you can join it at the end.

It’s a good practice to not modify the inputs, so I would suggest trying something like:

function titleCase(str) {
  var arr = str.toLowerCase().split(' ');
  for(var i=0 ; i < arr.length ; i++){
    arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
   // or: arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1); 
  }
return arr.join(' ');
}

which makes it also more readable, as you know that arr is an array.


#3

That makes sense, thank you so much for taking the time to answer. I knew it was a fault in my logic but couldn’t pin point it.

Have a nice day :slight_smile: