Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing Text in HTML with JavaScript

I'm trying to write a JavaScript program without the use of jQuery to replace all visible target text on a webpage without messing up the page's functionality.

Specifically I'm trying to make a Chrome extension that does it passively on sites such as Facebook.

I've experienced limited success with the following:

checkLoad();
function checkLoad(){
    if (document.readyState === "complete") {
        document.body.innerHTML = document.body.innerHTML.replace("target string", "replacement string");
    } else {
        setTimeout('checkLoad();', 500)
    }
}

This code misses things like people's names, titles and such.

I've looked around and can't seem to find a working solution. Any ideas?

like image 431
Andrew Avatar asked Nov 25 '12 00:11

Andrew


People also ask

Can you replace HTML with JavaScript?

One very useful ability provided by JavaScript is the ability to replace the content of elements in an existing HTML document that was previously displayed, even empty elements. There are many reasons that a web designer may choose to take advantage of this ability but providing interactive pages is a likely goal.

How do you replace words in JavaScript?

To replace text in a JavaScript string the replace() function is used. The replace() function takes two arguments, the substring to be replaced and the new string that will take its place. Regex(p) can also be used to replace text in a string.

How do you replace values in HTML?

One has to note that the replace() function will replace only the first occurrence of the specified value. In order to replace all occurrences, one has to use the global modifier. where 'valueToBeReplaced' can either be a string value or a regular expression.


3 Answers

Simple regular expression to fix it:

document.body.innerHTML = document.body.innerHTML.replace(/target string/g, "replacement string");
like image 118
Bruno Sousa Avatar answered Sep 25 '22 05:09

Bruno Sousa


I'd recommend against replacing the innerHTML for a few reasons from this blog (https://j11y.io/javascript/replacing-text-in-the-dom-solved/):

  1. You can't guarantee that the text replaced is text. Maybe it's an attribute in the html or other relevant code.
  2. It resets the document and, in my case, fired my chrome extension again. This led to my extension reloading again and again.

I solved this by downloading the js file from the blog and called it like so:

  var regex = new RegExp(targetString, "g");
  findAndReplaceDOMText(document.body, {
    find: regex,
    replace: function(portion) {
      var e = document.createElement('span');
      e.appendChild(document.createTextNode(replacementString));
      return e;
    }
  });

My use case above wraps the text being replaced in a span tag, so it's slightly different than yours. This javascript function has lots of flexibility.

like image 29
Joe B. Avatar answered Sep 23 '22 05:09

Joe B.


The link https://j11y.io/javascript/replacing-text-in-the-dom-solved/ is cool but I'm not 100% agree with a solution. IMHO walking on DOM could be overkill.

Here is my tricky solution working on regexp only so can element.innerHTML be used. So that replaces text everywhere except tags and nbsp-like things:

function highlightInHtml(html, textToHighlight) {
  const t = textToHighlight'

  const tagsRe = new RegExp('(<.+?>|&\\w+;)');

  const htmlParts = html.split(tagsRe).filter(Boolean);

  const r = htmlParts.map( item =>
    tagsRe.test(item)
      ? item
      : item.replace(new RegExp(`(${t})`, 'ig'), `<span class="highlight">$1</span>`)
  ).join('');

  return r;
}

If there is something weak in this solution please let me know!

like image 20
alex_1948511 Avatar answered Sep 25 '22 05:09

alex_1948511