JavaScript regex remove any prefix in perfect match

How can I remove "Dr", "Dr." or "dr" on a string?

"Dr. Drake Cohen" would become "Drake Cohen"
"Dr Drake Cohen" would become "Drake Cohen"
"Drake Cohen" would become "Drake Cohen"
"Rachel Smith" would become "Rachel Smith"
"Dr. Rachel Smith" would become "Rachel Smith"

      

What I have tried:

str.replace(/dr./i, "")

      

but this removes all instances of Dr

+3


source to share


1 answer


Go with this regex.

Regex: dr[\.\s]

case insensitive must be enabled.

Regex101 Demo

enter image description here




From revo's comment, it's much better to avoid matching dr

in names like Alexandr

.

Regex: \bdr[.\s]\s?

This will check word boundary

before dr

.

Regex101 Demo

+7


source







All Articles