简体   繁体   中英

Replacing Text with Treewalker in a Chrome Extension

I found the example below of how to replace text with Treewalker here: Javascript .replace command replace page text?

// create a TreeWalker of all text nodes
var allTextNodes = document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),
// some temp references for performance
tmptxt,
tmpnode,
// compile the RE and cache the replace string, for performance
cakeRE = /cake/g
replaceValue = "pie";

// iterate through all text nodes
while (allTextNodes.nextNode()) {
tmpnode = allTextNodes.currentNode;
tmptxt = tmpnode.nodeValue;
tmpnode.nodeValue = tmptxt.replace(cakeRE,replaceValue);
}

Would it be possible to modify this so it can check for and replace multiple words as well as not being case sensitive?

For a pattern to be case-insensitive, you can use the i flag. [ more info ]

If you want to replace multiple words with the one specific word, then just modify the regex pattern like this:

cakeRE = /word1|word2|.../gi;

If you want to replace each word with a different replacement value, you could create a set of corresponding pattern-replacement pairs and iterate over it. Eg:

...
patterns = [/cake/gi, /muffin/gi, /pancake/gi];
replacements = ["pie", "brownie", "cheese-cake"];
...
tmpnode = allTextNodes.currentNode;
patterns.forEach(function(pattern, idx) {
    tmpnode.nodeValue = tmpnode.nodeValue.replace(pattern, replacements[idx]);
});
...

Alternatively, you could also use the replace variation with a function as its 2nd param. [ more info ]

...
replDict = {
    "cake": "pie",
    "muffin": "brownie",
    "pancake": "cheese-cake"
};
pattern = new RegExp(Object.keys(replDict).join("|"), "gi");
...
tmpnode = allTextNodes.currentNode;
tmpnode.nodeValue = tmpnode.nodeValue.replace(pattern, function(match) {
    return replDict[match];
});
...

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