Javascript:regex用于替换文本中的单词而不是单词的一部分 [英] Javascript: regex for replace words inside text and not part of the words

查看:59
本文介绍了Javascript:regex用于替换文本中的单词而不是单词的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need regex for replace words inside text and not part of the words.

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

My code that replace 'de' also when it’s part of the word:

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

output==" gree ep "

我需要的输出:度深

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

What should be regex for get proper output?

推荐答案

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 _]

The \b denotes a "word boundary". A word boundary is defined as a position where a word character follows a non-word character, or vice versa. A word character is defined as [a-zA-Z0-9_] in JavaScript.

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

Start-of-string and end-of-string positions 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 character does not work very well outside the realm of the English language.

这篇关于Javascript:regex用于替换文本中的单词而不是单词的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆