为什么javascript中的.replace()会替换当时的"the"?

0 javascript regex

如果我这样做的话

var x="the dog then the cat ran";
var y=x.replace(/the/g,"");
Run Code Online (Sandbox Code Playgroud)

然后你会相等

"dog n cat ran" 
Run Code Online (Sandbox Code Playgroud)

从那时起删除(或替换)字母"the"之后,n将保留.

我该如何防止这种情况发生?

eli*_*ide 6

您需要添加边界标记,如下所示:

var x="the dog then the cat ran";
var y=x.replace(/\bthe\b/g,"");
// y = " dog then  cat ran"
Run Code Online (Sandbox Code Playgroud)

否则,/the/比赛then,breathe,thesis,等,一样容易the.\b需要一个单词边界.

如果你摆脱then它,试试这个:

var x="the dog then the cat ran";
var y=x.replace(/\bthe\S*\b/g,"");
// y = " dog    cat ran"
Run Code Online (Sandbox Code Playgroud)

要摆脱多余的空间:

var x="the dog then the cat ran";
var y=x.replace(/\bthe\S*\b\s*/g,"");
// y = "dog cat ran"
Run Code Online (Sandbox Code Playgroud)