Basic Algorithm Scripting: Title Case a Sentence//help

Tell us what’s happening:
I would like to replace the first letter in the string so as the first argument in the replace method I am inputting arr[i].charAt(0)
But this is only replacing first letters of the first three words
Can someone please explain why is arr[i].charAt(0) in the replace method not going till the end of the given variable
Also when I store arr[i].charAt(0) in a separate variable the result is himhhims which are the first letters of the returning string

Your code so far

function titleCase(str) {
  let lowerCase = str.toLowerCase();
  let arr = lowerCase.split(" ");
  for(let i = 0; i < arr.length; i++){

return str;


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36.

Challenge: Title Case a Sentence

Link to the challenge:

Notice that in the loop you have whole lowerCase text as string to replace. arr[i].charAt(0) is giving the correct character to replace, but replace changes the first occurrence of the character and in lowerCase that character is found sooner.

Don’t forget about adding to what found character should be replaced.

Also keep in mind that replace doesn’t change the original string and in the code snippet you provided you’re returning the same string provided in the arguments

I plan to save the return of the replace method in a variable and later return that variable but I haven’t yet figured out how to properly use the replace method :slight_smile:

I meant to reply to @IBanda

OK I would suggest you look at this

1 Like

It is going to the third word and then again from the beginning and this loop continues for arr.length but only to the third word in the string
So you say that it is because himhhims is found in the first three words and there is no need to continue to other words but isnt the (0) in charAt saying to look at only the first letters and arr[i] to look for arr.length number of times

arr[i].charAt(0) is just giving you the character to look for to replace, that doesn’t determine to which variable is later the actual replace applied.

function titleCase(str) {
  var newArr = [];
  var lowerCase = str.toLowerCase();
  var arr = lowerCase.split(" ");
  for(let i = 0; i < arr.length; i++){
    var letters = arr[i].charAt(0).toUpperCase();
    if(arr[i].length >= 1){
   var rest = arr[i].slice(1, arr[i].length);
   newArr.push(letters + rest)
        var newStr = newArr.join(" ")
return newStr

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

I found a workable solution. Thank you for your help