Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change String containing ' ,to TitleCase

Im able to change a normal string to title case using this.

return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});

Im not sure how to make a string like this to title case,

maureen o'hara -> Maureen O'Hara
maureen macnamee -> Maureen MacNamee
Maureen mctavis ->Maureen McTavis

Is this possible to do?

like image 509
AndroidAL Avatar asked Dec 11 '25 22:12

AndroidAL


1 Answers

You can use this code:

function nameToTC(input) {
  return input.replace(/\b(ma?c)?(\w)(\w*)/ig, function (m, grp1, grp2, grp3) {
    if (grp1) {
        return grp1.charAt(0).toUpperCase() + grp1.substr(1).toLowerCase() + grp2.toUpperCase() + grp3.toLowerCase();
    }
    else {
        return grp2.toUpperCase() + grp3.toLowerCase();
    }
  });
}
console.log(nameToTC('maureen o\'hara'));
console.log(nameToTC('maureen macnamee'));
console.log(nameToTC('Maureen mctavis'));

Result:

Maureen O'Hara
Maureen MacNamee
Maureen McTavis

The regex - \b(ma?c)?(\w)(\w*) - matches a word boundary first with \b, then optionally matches and captures into Group 1 mac or Mc, etc. with (ma?c)?, then matches and captures into Group 2 one alphanumeric symbol ((\w)) and then matches and captures into Group 3 0 or more final alphanumeric characters belonging to the current word (with (\w*)).

Inside the callback function, we check if Group 1 is set, if it is, we capitalize the mc or mac and then the rest. If Group 1 is not set, we do not handle that part and only capitalize Group 2.

like image 109
Wiktor Stribiżew Avatar answered Dec 13 '25 10:12

Wiktor Stribiżew