简体   繁体   中英

javascript regular expression remove complete words only

I try to use regular expression on javascript to remove some uneeded words. for ex., my base strings are 1. "David Guetta avi!" 2. "David Guetta avi bla bla" 3. "avi of David Guetta"

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.

If I use .replace(/avi/s,''); it will remove the avi also from David (will be 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.

You can also try

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

where [^a-zA-Z] is anything not in a-zA-Z .

I've combined @Evan answer into symbol removal regexp + double space removal and the final answer is:

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

thank you all :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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