I am trying to title case all of the words in a string using a RegEx.
I am using the following code (derived from another post) right now, but I think there has to be something better.
My processing is as follows:
- Convert entire string to Lower Case
- Convert the 1st letter of a word following a boundary (non-word character) to Upper Case
- Handle any case where the string starts with "mc" following a boundary by converting the 3rd character to Upper Case
The code is:
let text = "STEPHEN wells-o'shaugnessy mcdonald";
let result = text.toLowerCase().replace(/\b\w/g,(c) => c.toUpperCase());
result = result.replace(/\bmc\w/ig,(c) => c.charAt(0).toUpperCase() + c.charAt(1).toLowerCase() + c.charAt(2).toUpperCase());
result is: Stephen Well-O'Shaugnessy McDonald
I thought the following would work for names starting with "mc" but it does not, and I can't figure out why:
result = result.replace(/b(?:mc)\w/ig, (c) => c.toUpperCase());
My thought was that the "/(?:mc)" would match the characters "mc" following a boundary but ignore the match since it is a non-capturing match, globally and ignoring case
and the "\w" would match the next character
which would be converted to Upper Case in the (c) => c.toUpperCase()
Any help making this more concise and explaining why the last "replace" doesn't work would be appreciated.
Thanks,
Eric