Title Case a Sentence, javascript challenges

Tell us what’s happening:
Can anyone give a hint on this problem? I figured out that I should first convert all letters to lowercase and then start from there but I can’t correctly convert only the first letter of each string after splitting the array. Any Tips?

Your code so far


function titleCase(str) {
// Convert All of string to lowercase
// Split the string in array of elemens
// loop through each element and set first letter to uppercase, set
// the current array to the new version of the array with the uppercase first letter
// Join the modified array to a string adn then return the string

str = str.toLowerCase();
str = str.split(" ");

for(let i = 0; i<str.length; i++){
  str.splice(i, 1, str[i][0].toUpperCase());
  console.log(str);
}
}


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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence

I think part of the problem is your labeling.

Here:

str = str.split(" ");

You save that split string into the same variable. But the result isn’t a string, it’s an array. So then you loop over the array trying to splice letters into an array.

Take a step back. You’ve got a good start. You convert everything to lowercase. Then you split it into an array of strings. I would change it’s name at this point. I would do something like this:

function titleCase(str) {
  str = str.toLowerCase();
  const arr = str.split(" ");

  for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
  }
}

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

Now you can see what you are working with. You want to take each of those strings (arr[i]) and break it into two pieces so you can capitalize the first letter and then put it back together and then save it back into that same array slot. To break it apart, splice won’t work because it’s only for arrays and we’re breaking apart a string. I might suggest a string prototype method that rhymes with “slice”. Then you can reassemble the string with concatenation and drop it in the array. Does that make sense? Then all you’ll have to do is find a way to join everything back together again, the opposite of what you did with split.

Got It! I don’t know if I agree with you that the method i used rhymes with slice, but my solution did chain together 5 or so methods.

Thank you for the help!

There are other ways to do it, but I think using slice is the most straightforward. But if you have something that works, that’s the most important thing.