I need a JavaScript method to allows me to convert the first letter of every word in a string to a capital letter like this: mike tyson wayne to Mike Tyson Wayne.
The method should also be able to convert the first word after an hyphen to capital letter like this: mike-tyson wayne to Mike Tyson Wayne.
The method should also be able to convert uppercase words to capitalize words like this: MIKE-TYSON WAYNE to Mike Tyson Wayne.
I have tried this method using regular expression gotten from another thread:
text.replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase())
- (^\w{1}): match first char of string
- |: or
- (\s{1}\w{1}): match one char that came after one space
- g: match all
- match => match.toUpperCase(): replace with can take function, so; replace match with upper case match
It worked for converting the first letter of a string to capital letter and also works for the first letter of a string after space.
I added this expression that was supposed to cater for first letter of a string after space to the expression. The expression is (?:- |\d\. ).*
Combined with the first expression, it became:
text.replace(/(^\w{1})|(\s{1}\w{1})|(?:- |\d\. ).*/g, match => match.toUpperCase());
The problem is that the method above doesn't work for the strings after the dash but still works for the strings after space.