siddhartharora02
4/12/2017 - 7:03 AM

Title case a sentence - 2 methods

Title case a sentence - 2 methods

function titleCase(str) {
  str = str.toLowerCase()
    .split(' ')
    .map((word)=>{
        return word.charAt(0).toUpperCase()
        .concat(word.substr(1,word.length));
  });  
  
  var res = str.join(' ');
  return res;
}
//res here has a global scope and it doesn't disturb the res inside the function!
var res = titleCase("I'm a little tea pot");
console.log(res);

// we can also use replace for the 1st letter and make it uppercase. its easier and direct

function titleCase(str) {
  str = str.toLowerCase()
    .split(' ')
    .map((word)=>{
        return word.replace(word.charAt(0),word.charAt(0).toUpperCase());
  }).join(' ');  
  
  return str;
}