Title Case challenge

function titleCase(str) {
  str = str.replace(str[0], str[0].toUpperCase()); 
  for (i = 1; i < str.length; i++){
    if (str[i] == " "){
      str = str.replace(str[i + 1], str[i + 1].toUpperCase());
  return str;

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

This returns I’m A LitTle tea Pot
I’m trying to make it so every time it finds a space in a string it capitalizes the next character

The problem with this logic is when i = 12, str[12+1] = ‘t’, so your replace line is really:

str = str.replace('t', 'T');   

This will replace only the first occurrence of ‘t’ with ‘T’. The first ‘t’ is in the word ‘Little’, so the first ‘t’ of ‘Little’ gets capitalized to become ‘LiTtle’ and nothing happens to the ‘t’ in ‘tea’.

You can have a similar logic (looking for the space character), but instead of replacing str each time, you need to build a new string one character at a time and use toUpperCase when to replace a single character of the new string.

1 Like

Thanks for the help.