Help with Title Case a Sentence challenge

Help with Title Case a Sentence challenge
0

#1

Hi,

I am kind of stuck with this challenge.

I have this code that is giving me the following error : charAt is not a function

Code:

function titleCase(str) {
  var strLowerCase = str.toLowerCase().split(" ");
  var firstUpperCase = strLowerCase.map(function (firstUpper){
    firstUpperCase = strLowerCase.replace(strLowerCase.charAt(0), strLowerCase.charAt(0).toUpperCase());
    return firstUpperCase;
                                        });
  
  str = strLowerCase;
  return str;
}

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

to be honest I don´t fully understand why I receive this error, and I think I misunderstood something from the charAt() or map() functions.

Could anyone please shed some light?

Thank you!!

G.


#2

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

Well done so far.

charAt is a string function, but strLowerCase is an array

Your map function should take each element of the array and return something to replace it with

var firstUpperCase = strLowerCase.map(function (string){ return <what you want to return>; });

where firstUpperCase will be the new array (this is probably what you want to return from the outer function, after you ‘join’ it back into a string.

You can make new strings by concatenating pieces, eg; string = string[0] + string.slice(1)

I won’t spoil the fun for you completely.


#4

Thank you so much for the insight!

This means that whatever is inside the function brackets is the name of the string I have to use for my charAt function. am right?


#5

The first argument in the anonymous function of map represents the current element in the array being iterated over. When you wrote the following:

var firstUpperCase = strLowerCase.map(function (firstUpper){
  firstUpperCase = strLowerCase.replace(strLowerCase.charAt(0), 
  strLowerCase.charAt(0).toUpperCase());
  return firstUpperCase;
});

the firstUpper argument represents each word in the strLowerCase array. To make it more readable, I would rename firstUpper to word, because that is what each element of the strLowerCase array really is. Then, you would use the replace function on word instead of strLowerCase. Also, the following:

strLowerCase.charAt(0).toUpperCase());

does nothing, because you are not assigning it to anything. Of course, now you also know to replace strLowerCase with word.

So to answer your original question above, YES.