简体   繁体   中英

How to match and replace entire word that contains substring using Javascript RegExp

I'd like to match and replace the entire word that contains a substring using Javascript.

This is my code so far:

var final = ""
var n, a = [], walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false);
const searchWordPattern = new RegExp(searchWord, 'i');

while(n = walk.nextNode()) {
  a.push(n);
  n.nodeValue = n.nodeValue.replace(searchWordPattern, "--");
  final = final.concat(n.nodeValue);
}

This partially works. It finds the word I'm searching for and removes it. But if the search word is conjugated in any way, that gets left behind. I'd like for the regex to match the entire word where the substring is found. And remove it all. What do I need to change?

EDIT

I tried using the below answer, but it doesn't appear to do anything different for either the \\w or \\S variations. Here is the code I am using:

var final = ""
var n, a = [], walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false);
const searchWordPattern = new RegExp('\S*' + searchWord + '\S*', 'i');

while(n = walk.nextNode()) {
  a.push(n);
  n.nodeValue = n.nodeValue.replace(searchWordPattern, "--");
  final = final.concat(n.nodeValue);
}

The result is that the searchWord is replaced by the "--" string, but if it is conjugated it doesn't include the other characters. So if "look" is the searchWord, the result of the regex is "--ing". I want it to just be "--".

You need to adjust the regex, so that instead of just searching for the word:

new RegExp(searchWord, 'i');

You can also search for any surrounding "word" characters:

new RegExp('\\w*' + searchWord + '\\w*', 'i');

Or all the non-whitespace characters:

new RegExp('\\S*' + searchWord + '\\S*', 'i');

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