Simpler version of capitalizing each word in a string I have this code which does the job, however it seems to me that the same could be done with less code. And why if I put 'var newString = stored.join(' ');' below 'var stored=[];' the code doesn't work?

function titleCase(str) {

var lower = str.toLowerCase();

var arr = lower.split(' ');

var stored = [];

//takes a string from arr
for(var i = 0; i&lt;arr.length; i++) {

 //splits and stores the string to letters 
   var word = arr[i].split(''); // ['l','i','t'...]

    // takes the first letter from the array and makes it uppercase
   for(var k=0; k&lt;1; k++){
   var upper = word[k].toUpperCase(); 
   word.shift(); 
   word.unshift(upper);
   var joined = word.join('');
   stored.push(joined);
}

}
 var newString = stored.join(' ');

 return newString;

}

 titleCase("I'm a little tea pot");
You can use String#replace with a regexp:



function titleCase(str) {
  return str.toLowerCase() // change the string to lowercase
    .replace(/\S+/g, function(s) { // get all non space characters sequences
      return s.charAt(0).toUpperCase() + s.substring(1); // uppercase the 1st letter and combine with the rest of the string
    });
}

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