JavaScript正则表达式删除完美匹配上的任何前缀

时间:2017-04-27 17:16:34

标签: javascript regex

如何删除字符串中的“Dr”,“Dr.”或“dr”?

"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"

我尝试了什么:

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

但这会删除Dr

的所有实例

1 个答案:

答案 0 :(得分:7)

使用此正则表达式。

正则表达式: dr[\.\s]不区分大小写应该为ON。

Regex101 Demo

enter image description here

从revo的评论来看,最好避免在dr这样的名称中匹配Alexandr

正则表达式 \bdr[.\s]\s?这会在word boundary之前检查dr

Regex101 Demo