0

我在这里找到了如何用 Treewalker 替换文本的示例: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);
}

是否可以对其进行修改,以便它可以检查和替换多个单词并且不区分大小写?

4

1 回答 1

0

对于不区分大小写的模式,您可以使用该i标志。[更多信息]

如果您想用一个特定的单词替换多个单词,那么只需像这样修改正则表达式模式:

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

如果您想用不同的替换值替换每个单词,您可以创建一组相应的模式替换对并对其进行迭代。例如:

...
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]);
});
...

或者,您也可以使用replace带有函数的变体作为其第二个参数。[更多信息]

...
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];
});
...
于 2013-11-09T06:44:51.410 回答