Title Case a Sentence-3rd case is not satisfied

Title Case a Sentence-3rd case is not satisfied
0

#1

Why this code is not fulfiling all conditions.Help?
var array=[];
var newArray=[];
function titleCase(str) {
var newStr=str.toLowerCase();
var array=newStr.split(" ");
for(var i=0; i<array.length; i++){
newArray[i]=array[i].charAt(0).toUpperCase()+array[i].substring(1);

}
return newArray.join(" ");
}

titleCase(“sHoRt AnD sToUt”);


#3

The reason you are failing the 3rd case is because your array declarations are created outside the function resulting in global variables which are not reset between each test. Move your array declarations inside the function and then remove any duplicate var declarations of the same variable within the function. Also, since you only use the newArray variable within the for loop, you can get rid of the var newArray = []; and put var in front of the following statement:

newArray[i]=array[i].charAt(0).toUpperCase()+array[i].substring(1);

Making all the above changes results in the following code

function titleCase(str) {
  var array=[];
  var newStr=str.toLowerCase();
  array=newStr.split(" ");
  for(var i=0; i<array.length; i++){
    var newArray[i]=array[i].charAt(0).toUpperCase()+array[i].substring(1); // added var
  }
  return newArray.join(" ");
}

#4

We can do it without variables.

function titleCase(str) {
    return str.toLowerCase().split(' ').map(function(word) {
            return word.charAt(0).toUpperCase() + word.substring(1);
    }).join(' ');
}

titleCase('sHoRt AnD sToUt');