Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace text in a website

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.

like image 636
Numeri Avatar asked Aug 27 '13 20:08

Numeri


People also ask

How do you replace text in HTML?

Simple find and replace of text in HTML The same can be done with Ctrl+C (copy) and Ctrl+V (paste). Then add replacement text (4) or leave it empty if you want to delete given text occurrences from HTML. Click Add button (5).

How do you replace a text?

Find and replace basic text , type the word or phrase that you want to find, and Word will highlight all instances of the word or phrase throughout the document. To replace found text: Select the magnifying glass, and then select Replace. In the Replace With box, type the replacement text.

How do you find and replace in inspect?

Alternatively if you want to search and replace in the HTML you could Right Click → Edit as HTML the <body> in the DevTools Elements Panel select all the text with Ctrl + a , paste into your favourite editor, make the change there and paste it back.


1 Answers

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);
}
like image 200
Paul Avatar answered Oct 28 '22 11:10

Paul