Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:regex,用于替换文本中的单词,而不是单词的一部分_Javascript_Regex - Fatal编程技术网

Javascript:regex,用于替换文本中的单词,而不是单词的一部分

Javascript:regex,用于替换文本中的单词,而不是单词的一部分,javascript,regex,Javascript,Regex,我需要正则表达式来替换文本中的单词,而不是单词的一部分 当“de”是单词的一部分时,我的代码也会替换它: str="de degree deep de"; output=str.replace(new RegExp('de','g'),''); output==" gree ep " 我需要的输出:“degree deep” 要获得正确的输出,正则表达式应该是什么 str.replace(/\bde\b/g, ''); 注意 RegExp('\\bde\\b','g') // re

我需要正则表达式来替换文本中的单词,而不是单词的一部分

当“de”是单词的一部分时,我的代码也会替换它:

str="de degree deep de";
output=str.replace(new RegExp('de','g'),''); 

output==" gree ep "
我需要的输出:
“degree deep”

要获得正确的输出,正则表达式应该是什么

str.replace(/\bde\b/g, ''); 
注意

RegExp('\\bde\\b','g')   // regex object constructor (takes a string as input)

都是一样的

\b
表示“单词边界”。单词边界定义为单词字符跟随非单词字符的位置,反之亦然。在JavaScript中,单词字符定义为
[A-zA-Z0-9.]

字符串的起始位置和结束位置也可以是单词边界,只要它们后面或前面分别有一个单词字符


请注意,单词字符的概念在英语以外的领域中并不适用。

您可以使用reg-ex
\bde\b

str="de degree deep de";
output=str.replace(/\bde\b/g,''); 
你可以找到一个工作样本


正则表达式字符
\b
用作单词分隔符。您可以找到更多信息。

您应该将搜索字符括在
\b
之间:

str="de degree deep de";
output=str.replace(/\bde\b/g,''); 

您可以使用单词边界作为Arun&Tomalak注释

/\bde\b/g

或者你可以使用一个空格

/de\s/g

str="de degree deep de";
output=str.replace(/\bde\b/g,'');