Title Case Sentence, how did I do?

Title Case Sentence, how did I do?
0

#1

Hey, all. I just finished the Title Case Sentence challenge, and it almost broke my brain. After some thinking and googling this is what I came up with. How did I do? I’m sure there are shorter/simpler ways of doing this, but would this be reasonable for actual application?

  function titleCase(str) {
      
      var secondArray = [];
      
      var newStr = str.toLowerCase();
      
      //split the string into an array of strings
      var firstArray = newStr.split(" ");
      
      //Do all the things
      for (var i = 0; i < firstArray.length; i++){
        var a = firstArray[i].substr(0,1).toUpperCase();
        var b = firstArray[i].substr(1);
        var result = a + b;
        secondArray.push(result);
      }
      
      //recombine array into one string
      var finalStr = secondArray.join(" ");
      
      //return result
      return finalStr;
    }

#2

I am not sure if yours would be reasonable or not, here is what I did if this helps:

function titleCase(str) {
  var words = str.split(' ');
  
  for (var index = 0; index < words.length; index++) {
    words[index] = words[index].charAt(0).toUpperCase() + words[index].slice(1).toLowerCase();
  }
  
  return words.join(' ');
}

titleCase("sHoRt AnD sToUt");

#4

Thanks! It’s really helpful


#5

:slight_smile: Thank you! It’s good to hear, and really good to see more advanced ways of doing it


#6

Could be shortened.
`function titleCase(str) {
str=str.toLowerCase();
var array=str.split(/\s+/);
array=array.map(function(val){
return val[0].toUpperCase()+val.substring(1);
});
return array.join(" ");
}

titleCase(“I’m a little tea pot”);`


#7

function titleCase(str) {
var arr=str.toLowerCase().split(’’);
for (var i=0;i<arr.length;i++){
if (arr[i]===" "){
arr[i+1]=arr[i+1].toUpperCase();
}
}
arr[0]=arr[0].toUpperCase();
var end=arr.join(’’);
return end;
}

titleCase(“I’m a little tea pot”);


#8

u did great, mine was too long, its cringe worthy :sweat_smile:

function titleCase(str) {
  var arr = [],arr2 = [],arr3=[],arr4=[],letter;
  arr = str.split(' ');
  
  for(var i=0;i<arr.length;i++){
arr2.push(arr[i].split(''));

for(var j=0;j<arr2[i].length;j++){
  if(j===0){
    
    letter = arr2[i][j].toUpperCase();
    arr2[i][j] = letter;
  }
  else {
    letter = arr2[i][j].toLowerCase();
    arr2[i][j] = letter;
  }
}
arr3 = arr2[i].reduce(function(prev, curr) {
  return prev.concat(curr);
  });
arr4.push(arr3);
  }
  
  str = arr4.join(' ');
  
  return str;
}

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

#9

This was a perfect place to use the Map method.

  function titleCase(str) {
  var happy = str.toLowerCase().split(' ');
    return happy.map(function(word) {
      return word[0].toUpperCase() + word.substr(1);
    })
    .join(' ');
  }

#11