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.