简体   繁体   English

javascript正则表达式仅删除完整的单词

[英]javascript regular expression remove complete words only

I try to use regular expression on javascript to remove some uneeded words. 我尝试在JavaScript上使用正则表达式来删除一些不需要的单词。 for ex., my base strings are 1. "David Guetta avi!" 例如,我的基本字符串是1.“ David Guetta avi!” 2. "David Guetta avi bla bla" 3. "avi of David Guetta" 2.“ David Guetta avi bla bla” 3.“ David Guetta的avi”

I want to remove the "avi", as you see, in the 1st string the avi wrapped by space and exclamation mark, the 2nd string wrapped by spaces and the 3rd wrapped by space in the right side only. 如您所见,我想删除“ avi”,在第一个字符串中,用空格和感叹号包裹的avi,仅在右边的空格中包裹第二个字符串,用空格包裹的第三个字符串。

If I use .replace(/avi/s,''); 如果我使用.replace(/ avi / s,''); it will remove the avi also from David (will be Dd). 它将同时从David中删除avi(将为Dd)。 I need help with write regexp which will remove the specific word which not wrapped or wrapped by symbols (also spaces slashes whatever). 我需要有关写正则表达式的帮助,该规则将删除没有用符号包裹(或空格用斜杠代替)的特定单词。

Thanks :) 谢谢 :)

Have you tried using the word boundary special character? 您是否尝试过使用边界特殊字符一词? So the regex would be: 因此正则表达式将是:

\b<word>\b

What about 关于什么

\W\avi\W{0,1}

The \\W stands for any non-word character. \\W代表任何非单词字符。

You can also try 您也可以尝试

[^a-zA-Z]avi[^a-zA-Z]{0,1}

where [^a-zA-Z] is anything not in a-zA-Z . 其中[^a-zA-Z] 不在 a-zA-Z

I've combined @Evan answer into symbol removal regexp + double space removal and the final answer is: 我已经将@Evan答案合并为符号删除正则表达式+双倍空格删除,最终答案是:

mystring.replace(/[^\\w\\s]|\\bavi\\b|\\s{2,}/gi,'');

thank you all :) 谢谢你们 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM