Trying to capitalise letters in a string with logic!

Hey all. Was hoping for a gentle nudge in the right direction. I’m on the
Basic Algorithm Scripting: Title Case a Sentence challenge. I need to capitalise the first letter of every word. This is what I have so far…

function titleCase(str) {
let lowerCase = str.toLowerCase();
let sentence = lowerCase.charAt(0).toUpperCase() + lowerCase.slice(1);  
  
  for (let i = 0; i < sentence.length; i++) {
    if (sentence[i] === " ") {
      console.log(sentence.charAt[(i + 1)]);
    }
  }
    
  return sentence;
}

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

First step in the function is to change the complete string to lowercase in case I have a string passed that is completely capitalised. The second step is to capitalise the first letter of the string and store the result in the variable sentence.

Then I was going to use a for loop to look for any white spaces in the string. If it finds a space, I would then capitalise the very next letter in the sting. At the moment I’m just trying to console.log that letter. But something isn’t working. I was hoping to just use the toUpperCase method on the selected letter and that would do the job. Any tips? Am I nearly there. Any help would be gratefully received.

I don’t remember the order of the lessons back then, but do you know String.split() yet?

Hi Chad. Thanks for your reply. Yeah I just looked at the first hint on the challenge and it said about splitting the words up into an array. That made perfect sense. The separate word strings would be much easier to manipulate than what I was trying to do!! I guess that’s all part of learning. Try to do something the long way and then realise there is a much more efficient way to do it!

1 Like

As for why what you’re trying to do isn’t working, you have a syntax error. sentence.charAt[(i + 1)]. You have a set of square brackets where they don’t belong.

(This challenge is easier if you use split(), as @ChadKreutzer suggests, but your method can work.)

1 Like

Thank you Ariel for your help with the syntax. I have learnt a lot on this challenge!

Good show! No real need to reinvent the wheel, but it can be good practice. :slight_smile:

Glad I could help. Happy coding!