Search code examples
javascriptstringuppercasewords

Changing the first letters of words in a string to uppercase in javascript


Can we capitalize the first letters of words in a string to Uppercase and return the string without using slice(1) in javascript? If possible please help me find this out?

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

Solution

  • You can use String#replace with a regular expression:

    function titleCase(str) {
      return str.toLowerCase().replace(/\b\w/g, function(m) {
        return m.toUpperCase();
      });
    }
    
    console.log(titleCase("sHoRt AnD sToUt"));