Javascript:用于替换文本中的单词而不是单词的一部分的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4921701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: regex for replace words inside text and not part of the words
提问by Yosef
I need regex for replace words inside text and not part of the words.
我需要正则表达式来替换文本中的单词而不是单词的一部分。
My code that replace 'de' also when it's part of the word:
我的代码在它是单词的一部分时也会替换“de”:
str="de degree deep de";
output=str.replace(new RegExp('de','g'),'');
output==" gree ep "
Output that I need: " degree deep "
我需要的输出: " degree deep "
What should be regex for get proper output?
什么应该是正则表达式以获得正确的输出?
回答by Tomalak
str.replace(/\bde\b/g, '');
Note that
注意
RegExp('\bde\b','g') // regex object constructor (takes a string as input)
and
和
/\bde\b/g // regex literal notation, does not require \ escaping
are the same thing.
是一样的。
The \b
denotes a "word boundary". A word boundary is defined as a position where a wordcharacter follows a non-wordcharacter, or vice versa. A word character is defined as [a-zA-Z0-9_]
in JavaScript.
在\b
表示“单词边界”。单词边界定义为单词字符跟在非单词字符之后的位置,反之亦然。单词字符[a-zA-Z0-9_]
在 JavaScript 中定义。
Start-of-stringand end-of-stringpositions can be word boundaries as well, as long as they are followed or preceded by a word character, respectively.
字符串开头和字符串结尾位置也可以是单词边界,只要它们后面或前面分别有一个单词字符即可。
Be aware that the notion of a word characterdoes not work very well outside the realm of the English language.
请注意,单词字符的概念在英语语言领域之外并不适用。
回答by PatrikAkerstrand
str="de degree deep de";
output=str.replace(/\bde\b/g,'');
回答by Arun P Johny
回答by Don
You should enclose your search characters between \b
:
您应该将搜索字符括在 之间\b
:
str="de degree deep de";
output=str.replace(/\bde\b/g,'');
回答by knowledge_is_power
You can use a word boundary as Arun & Tomalak note.
您可以使用单词边界作为 Arun & Tomalak 注释。
/\bde\b/g
/\bde\b/g
or you can use a space
或者你可以使用一个空格
/de\s/g
/de\s/g