【发布时间】:2017-05-19 01:26:03
【问题描述】:
这是Replace text in a website 的后续帖子。
@Paulpro 给出的关于替换网站中的文本的最佳答案就像一个魅力,但我不知道如何在最后一行使用正则表达式:
replaceTextOnPage('original text', 'new text')。
我尝试使用类似的东西
replaceTextOnPage(/(?!bingogame)bingo/g, 'bridge')
将文本 'bingo' 替换为 'bridge'(不包括在 'bingogame' 中找到的匹配项),但整个脚本被搞砸了:
function replaceTextOnPage(from, to){
getAllTextNodes().forEach(function(node){
node.nodeValue = node.nodeValue.replace(new RegExp(quote(from), 'g'), to);
});
function getAllTextNodes(){
var result = [];
(function scanSubTree(node){
if(node.childNodes.length)
for(var i = 0; i < node.childNodes.length; i++)
scanSubTree(node.childNodes[i]);
else if(node.nodeType == Node.TEXT_NODE)
result.push(node);
})(document);
return result;
}
function quote(str){
return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
}
replaceTextOnPage(/(?!bingogame)bingo/g, 'bridge')
谁能告诉我如何正确地合并正则表达式?原谅我的愚蠢;奶奶在这里说话。
【问题讨论】:
-
quote 函数需要一个字符串,但您传入的是正则表达式文字。在回答您的原始问题时,传递给 replaceTextOnPage 的两个参数都是字符串。这可能不会导致错误,但我会三次检查 quote(regex literal) 的结果是否是您期望的模式。
-
该链接显示了当不使用正则表达式时脚本是如何工作的,以及在我包含正则表达式的情况下它是如何失败的。 link我不知道怎么改... :(
标签: javascript html