"Title Case a Sentence" challenge isn't accepted even good results

Hi, Anyone knows why this solution is not acceptable by FreeCodeCamp?
my code:


function titleCase(str) {
  str=str.toLowerCase();
  var a = str.split(' ');
  var x = " ";
  var z = [" "];
  var y= " ";
   for(var i=0;i<a.length;i++)
     {
       
       y=a[i];
       x=x+y.charAt(0).toUpperCase()+ y.slice(1)+" ";
   
     }
  
  return x;
}

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

You code outputs unnecessary spaces at the beginning and end. Instead of "I’m A Little Teapot"
you get " I’m A Little Teapot "

1 Like

you do have an extra varaible, but here is my solution… not sure what’s going on there.

/*
function titleCase(str) {

var arr=str.split(’ ');//split a ’ '
for(var i=0; i<arr.length; i++){ //for loop checking each place in array

var a = arr[i];// puts array str (word) into a variable a
var B= a.charAt(0).toUpperCase();//takes first leter, puts in B and capitolizes it
a = a.slice(1,a.length).toLowerCase();//now takes word from 2nd letter and lowers it
arr[i]= B.concat(a); //concat (combines) Upper letter stored in B with rest of Lowr word in 'a' and assigns it back to array

}
str=arr.join(’ ');//joins array with spaces and reassigns str
return str;

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

1 Like

Thank’s guys for help! Every answer is very helpful!