Title Case a Sentence - Help!

Hey, just doing the Title Case a Sentence Challenge.

I came up with this code:

function titleCase(str) {
  var words = str.split(" ");
  
  for (var i = 0; i < words.length; i++) {
    words[i][0].toUpperCase();
  }

  words = words.join(" ");

  return words;
}

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

Why isn’t that working?

Strings in javascript are immutable. So when you call

words[i][0].toUpperCase();

it returns a new string. It doesn’t modify words[i][0].

1 Like

The toUpperCase() method returns the value of the string converted to upper case. toUpperCase() does not affect the value of the string itself. You need to assign the conversion to another variable which will then have the capital letter in it.

While in the for loop, your codes needs replace each word in the words array with the uppercase variable combined with the remaining characters of the word which all need to be lowercase.

1 Like

You need to concatenate the rest of the lowercase letters to the same words[i]

function titleCase(str) {
  var words = str.toLowerCase().split(" ");
  
  for (var i = 0; i < words.length; i++) {
    words[i] = words[i][0].toUpperCase() + words[i].substr(1, words[i].length);
    console.log(words);
  }

  return words.join(" ");
}
1 Like

This code works, thank you!

But can you explain why words[i][0].toUpperCase() is now working?

Also in the solution I found this code:

String.prototype.replaceAt = function(index, character) {
    return this.substr(0, index) + character + this.substr(index+character.length);
};


function titleCase(str) {
    var newTitle = str.split(' ');
    var updatedTitle = [];
    for (var st in newTitle) {
        updatedTitle[st] = newTitle[st].toLowerCase().replaceAt(0, newTitle[st].charAt(0).toUpperCase());
    }
    return updatedTitle.join(' ');
}

They are using a for in loop. But as I learned before, for in loops are used in objects to iterate trough object property names?

It was working in your code before… but you’re not assigning the results to anything. So at the end of your for…loop, nothing was changed in your words[] array. It still contains the original str.

In the corrected code, you see it being assigned back to words[i].

PLUS… this is just the first letter of the word. You forgot to add the rest of the word.
The

+ words[i].substr(1, words[i].length) 

takes care of adding the rest of word.

PLUS… you didn’t take into account the condition of “what if a letter in the middle of the word, or the rest of the words are uppercase?”

so to take account of these conditions, it’s better to lowercase everything first, before you work on capitalizing the start of each word.

str.toLowerCase().split(" ")
1 Like

Now everything’s clear. Thanks you so much, dude!