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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With