0

I want to use regex to replace the lowercase letter of every word within a string of words, with an uppercase, ie change it to title case such that str_val="This is the best sauce ever" becomes "This Is The Best Sauce Ever". Here is my code

function (str_val) {
   let reg_exp = /\s\w/g;
   let str_len = str_val.split(' ').length;

   while (str_len){
      str_val[x].replace(reg_exp, reg_exp.toUpperCase());
      x++;
      str_len--;
   }
   return str_val;
}

How do I solve this with regex?

wanjd
  • 11
  • 4

1 Answers1

2

Use below function for title case

function title(str) {
   return str.replace(/(?:^|\s)\w/g, function(match) {
    return match.toUpperCase();
   });
}
Sachin
  • 789
  • 5
  • 18