这是 Replace text in a website 线程的后续内容.
@Paulpro 给出的关于替换网站中文本的最佳答案就像一个魅力,但我不知道如何在最后一行使用正则表达式:
replaceTextOnPage('原始文本', '新文本')
。
我尝试使用类似的东西
replaceTextOnPage(/(?!bingogame)bingo/g, '桥')
将文本'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 函数(如果您传入字符串,则允许它运行)。
尝试一下:
function quote(str){
// don't do anything if the parameter is an object (regex literal)
if (typeof str == 'object') return str;
return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
关于javascript - 在文本替换 javascript 中使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44053510/