Excercise: Title Case a Sentence

Excercise: Title Case a Sentence
0

#1

I have been trying to finish this algorithm. I am probably doing it a very inefficient way, but that’s OK to me because I understand why I am using the code that I am using. What I don’t understand is what I am doing wrong (which is probably a lot, I’m fairly new to this). Can someone tell me what I am doing wrong?

Here is what I have so far:

function titleCase(str) {
  str.toLowerCase();
  var array = str.split(" ");
  array[0][0].toUpperCase();
  array[1][0].toUpperCase();
  array[2][0].toUpperCase();
  array[3][0].toUpperCase();
  array[4][0].toUpperCase();

  if (array[5][0] == true) {
  array[5][0].toUpperCase;
  }
  if (array[6][0] == true) {
  array[6][0].toUpperCase;
  }
  if (array[7][0] == true) {
  array[7][0].toUpperCase;
  }

  var joined = array.join(" ");
  return joined;
  }

  titleCase("I'm a little tea pot");

#2

Recall that strings are immutable.


#3

As ArielLeslie said, strings are immutable. And remember that .toUpperCase() is a method (and so a function) which gives you a return value. So every time you do this:

you will get a return acording to your input, in this cas the return will be only the first letter of the string capitalized and not the whole string with the first letter in uppercase. Which if you wanted to use you should store it inside a variable or use it in another function( eg. x.map(), x.replace(), etc ), if not, is lost.
Try this in the console:
var str = “Hello”;
str.toUpperCase();

First check the return value that you get there. And then try to chek the value for the variable str. that will make clear what .upperCase is actually doing.

And as last point, remember that if you have to write code that targets the same variables like that it is better to loop through it.


#4

Thanks that is a big help. One day this will all make sense to me.