1

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");
Dinesh Nadimpalli
  • 1,441
  • 1
  • 13
  • 23

1 Answers1

2

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"));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209