Title Case a Sentence Challenge Issue

I would like to know why the code below is not a correct solution for the Title Case a Sentence Challenge.


function titleCase(str) {
  var arr = str.split('');
  var arr2 = arr.map(function(item){
     var individualItem = item[0].toUpperCase + item.slice(1);
    return individualItem ;
  });
  
  return arr2.join('');
}

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

  1. toUpperCase is a function, so you need parentheses
  2. str.split("") will split the string into an array of letters, but you only want to capitalize the first letter of each word
1 Like

@godwinekuma - my friend my approach has been quite different -

1)I convert all str to lower case …
2)Then i look for " " in the array , as i know the character after space has to be capital, as i have converted all to lower i am not worried about other variations
3)I then splice the value where there is space + 1 to upper case
4)Then i convert the first one to upper case , simple :slight_smile:

yes you will face some tougher variation of these later , try and use control statement and loops along with ready made functions like map …

Note - Just to add a point when we work with ready made functions like map , its more a syntax error here and there, but when we use control and loops , like below , there is logic , as the ready made methods hide logic , we need to use our own thinking to solve … earlier i solved as per others thinking now i solve as per my own thinking …



function titleCase(str) {
  
    
     str = str.toLowerCase();
    var newStr = str.split("");
    var test = [];
    
    for(var i =0; i < newStr.length; i++){
        
      if(newStr[i] === " "){
            //console.log(i);
            test = newStr.splice(i+1,1,newStr[i+1].toUpperCase());
        }
        
        else if(i === 0){
            test = newStr.splice(i,1,newStr[i].toUpperCase());
        }
       
    }
    newStr = newStr.join("");
    console.log(newStr);
}




titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")
1 Like