0

So I'm writing JS for a bookmarklet that will scour the page I'm in for specific words. Once found those words would then be replaced with something else. This only happens client side, on my web browser.

This is what I have so far:

const replaceString = function (condition, target, replacement) {
    /* Stop if page doesn't have CONDITION in it somewhere */
    if (!document.body.textContent.includes(`${condition}`)) return false;

    /* Turn TARGET string into a regular expression (e.g. 'Foo' -> /Foo/gi) */
    const regTarget = new RegExp(target, 'gi');

    /* Search for hits and replace them with REPLACEMENT */
    document.body.innerHTML = document.body.innerHTML.replace(regTarget, replacement);
};

replaceString('overflow', 'Foo', 'Bar');

This code successfully checks if the site contains 'overflow' somewhere. If it does then it scours for 'Foo' and subsequently replaces it with 'Bar'. Works neatly.

Except it doesn't only apply to text, it also changes HTML attributes. So if there's an element like img href="Foo.png" it would turn into img href="Bar.png", breaking the link.

How would you change the code so it only applies the desired change to plain text?

I'm moderately savvy with Javascript, but Regex is an entirely new thing for me and I got this far after going through several threads about replacing words. It's imperative for my purposes that the code goes through the entire page. Like, say, a wiki article containing a lot of 'Foo' that I want to display as 'Bar' instead, but don't want the image links and such to break.

Writing this, the editor suggested some threads with similar issues, but I couldn't figure out the solution to mine from what was written there. XML parser sounded promising, but I know nothing about it.

Savreth
  • 1
  • 1
  • 4
    It's never a good idea to use regexes with HTML. If you are working with HTML, then you should be using an HTML parsing library. Parse it to objects, then work with the objects. – Tim Roberts Feb 24 '23 at 18:28
  • Check [this](https://stackoverflow.com/a/50537862/9499523) answer! or you can use a [library](https://github.com/padolsey/findAndReplaceDOMText) to do it. – Joshua Ooi Feb 24 '23 at 19:18
  • [This one](https://stackoverflow.com/a/62122070/21281060) from @JoshuaOoi's link seems to work as intended. I'll do further testing tomorrow for bugs, but for now I'd say my question is answered. – Savreth Feb 27 '23 at 23:15

0 Answers0