Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在文本中使用正则表达式替换javascript_Javascript_Html - Fatal编程技术网

在文本中使用正则表达式替换javascript

在文本中使用正则表达式替换javascript,javascript,html,Javascript,Html,这是在的线程的后续 @Paulpro给出的关于在网站中替换文本的首要答案非常有魅力,但我不知道如何在最后一行使用正则表达式: replaceTextOnPage(“原始文本”、“新文本”) 我试着用类似于 replaceTextOnPage(/(?!bingogame)bingo/g,'bridge') 将文本'bingo'替换为'bridge'(不包括在'bingogame'中找到的匹配项),但整个脚本被以下内容弄乱了: function replaceTextOnPage(from, to)

这是在的线程的后续

@Paulpro给出的关于在网站中替换文本的首要答案非常有魅力,但我不知道如何在最后一行使用正则表达式:

replaceTextOnPage(“原始文本”、“新文本”)

我试着用类似于

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')
function replaceTextOnPage(从,到){
getAllTextNodes().forEach(函数(节点){
node.nodeValue=node.nodeValue.replace(新的RegExp(引号(from),'g'),to);
});
函数getAllTextNodes(){
var结果=[];
(函数扫描子树(节点){
if(node.childNodes.length)
对于(var i=0;i
有人能告诉我如何正确地合并正则表达式吗?请原谅我的愚蠢;奶奶在这里说话。

你应该把

var text=document.getElementsByTagName(“p”)[0];
//只匹配“宾果”
text.innerText=text.innerText.replace(/\bbingo\b/gi,“桥”)

bingoo bingoo bbingo bingogame bingo bingo游戏bing bingogame

我认为如果您传入正则表达式文本,您希望跳过调用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");
}

quote函数需要一个字符串,但您正在传入一个正则表达式文本。在对原始问题的回答中,传递到replaceTextOnPage的两个参数都是字符串。这可能不会导致错误,但我会三次检查quote(regex literal)的结果是否是您期望的模式。该链接显示了在不使用正则表达式时脚本如何工作,以及在包含正则表达式时脚本如何失败。我不知道如何改变它…:(谢谢你的回答!这个方法有效,但我忘了提到网站使用javascript,不幸的是,上面的方法会弄乱网站的代码。这就是为什么需要@Paulpro给出的方法。哦,天哪……它有效!不确定如何工作,因为我在使用计算机时几乎是脑死亡~但非常感谢,詹姆斯!:):)再次捐款~