What are differences between these two "Title Case a Sentence" codes?

What are differences between these two "Title Case a Sentence" codes?
0.0 0

#1

I passed this challenge but the first solution I came up didn’t work. And I can’t understand why it’s not working even all results fit with expectations. Is there anyone to explain me why?

The code who gives expected output but doesn’t pass. :point_down:

function titleCase(str) {
  var total=[];
  str = str.toLowerCase().split(" ");
  for(i =0; i<str.length; i++){
    total += str[i][0].toUpperCase() + str[i].slice(1).toLowerCase() + " ";
  }
  return total;
}

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

The code I passed the challenge :point_down:


function titleCase(str) {
  var arr = str.split(" ");
  var newArr = arr.map(function(val){
    var x = val[0].toUpperCase() + val.slice(1).toLowerCase();
    return x;
  });
  return newArr.join(" ");
}

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

Your browser information:

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

Link to the challenge:


#2

Your first solution sticks an extra space on the end.


#3

Thanks. Now I understood. But do you have any idea to fix that problem?


#4

total += str[i][0].toUpperCase() + str[i].slice(1).toLowerCase() + " ";
This is the line that adds a space after every word.

  • You could change the logic of adding a space so that it doesn’t happen after the last word
  • You could remove the space at the end of the string after your for loop.
  • You could create your string with a .join() instead of constructing it in the loop.