替换网站中的文字 [英] Replace text in a website

查看:91
本文介绍了替换网站中的文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript替换网页中的文本(我想运行它的任何网页)。我不是JavaScript的专家,所以我有点失落。如果我可以提供帮助,我想避免使用jQuery。



通过Google,我发现这个 stackoverflow问题。但是当我将 document.body.innerHTML = document.body.innerHTML.replace('hello','hi'); 注入网页时, 。它似乎使页面恢复为基本文本和格式。

另外,我想知道是否来自 here ,可以使用。再次,我真的不知道如何使用它。它会做的只是替换网页文本 - 而不是链接或文件名。



我使用Google Chrome incase这件事。



 

code> function replaceTextOnPage(from,to){
getAllTextNodes()。forEach(function(node){
node.nodeValue = node.nodeValue.replace(new RegExp(quote(from), 'g'),to);
});

函数getAllTextNodes(){
var result = [];

(函数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);

返回结果;


函数quote(str){
return(str +'')。replace(/([。?* + ^ $ [\] \\( ){} | - ])/ g,\\ $ 1);
}
}



>用法:

  replaceTextOnPage('hello','hi'); 

请注意,您需要 SHIM forEach ,或者用如下代码循环替换该代码:

  var nodes = getAllTextNodes(); 
for(var i = 0; i< nodes.length; i ++){
nodes [i] .nodeValue = nodes [i] .nodeValue.replace(new RegExp(quote(from),' g'),to);
}


I'm looking to replace text in a webpage (any webpage I want to run it on) using JavaScript. I'm not an expert in JavaScript, so I am sort of lost. If I can help it I would like to avoid jQuery.

Through Google, I've found this stackoverflow question. But when I inject document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi'); into a webpage it sort of messes the page up. It seems to make the page revert to basic text and formatting.

Also, I'm wondering if the regex code from here, could be used. Again, I really am not sure how to use it. What it would do is replace only webpage text - not links or filenames.

I'm using Google Chrome incase that matters.

解决方案

You could perform your repleacements on all the just the text nodes in the DOM:

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");
  }
}

Quote function borrowed from this answer.

Usage:

replaceTextOnPage('hello', 'hi');

Note that you will need to SHIM forEach in older browsers or replace that code with a loop like so:

var nodes = getAllTextNodes();
for(var i = 0; i < nodes.length; i++){
    nodes[i].nodeValue = nodes[i].nodeValue.replace(new RegExp(quote(from), 'g'), to);
}

这篇关于替换网站中的文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆