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

时间:2011-02-07 13:12:48

标签: javascript regex

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

我的代码替换'de'也是它的一部分:

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

output==" gree ep "

我需要的输出:" degree deep "

什么应该是正则表达式才能获得正确的输出?

5 个答案:

答案 0 :(得分:18)

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

请注意

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

/\bde\b/g                // regex literal notation, does not require \ escaping

是一回事。

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

字符串开头字符串结尾位置也可以是字边界,只要它们分别跟随或前面有单词字符

请注意,单词字符的概念在英语范围之外不能很好地发挥作用。

答案 1 :(得分:2)

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

答案 2 :(得分:2)

您可以使用reg ex \bde\b

您可以找到工作样本here

正则表达式字符\b充当单词分隔符。您可以找到更多here

答案 3 :(得分:2)

您应将搜索字符括在\b

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

答案 4 :(得分:1)

你可以使用单词边界作为Arun& Tomalak注意。

/ \ BDE \ B / G

或者您可以使用空格

/解\ S / G

http://www.regular-expressions.info/charclass.html

相关问题