This is almost always a bandage solution, but if you need a quick fix, use this gist:
Here's a sample JavaScript code that uses the replace method to replace a specific text with another text on a web page:
// replace "oldText" with "newText"
document.body.innerHTML = document.body.innerHTML.replace(/oldText/g, "newText");
This code will search for all occurrences of "oldText"
in the web page's HTML content and replace them with "newText"
. The g
flag in the regular expression /oldText/g
is used to replace all occurrences of "oldText"
, not just the first one.
Note that this code will replace text in all elements of the page, including HTML tags and attributes. If you want to replace text only in specific elements, you'll need to modify the selector accordingly. For example, to replace text only in paragraphs (<p>
tags), you could use:
// replace "oldText" with "newText" only in paragraphs
var paragraphs = document.getElementsByTagName("p");
for (var i = 0; i < paragraphs.length; i++) {
paragraphs[i].innerHTML = paragraphs[i].innerHTML.replace(/oldText/g, "newText");
}
This code will loop through all <p>
elements on the page and replace "oldText"
with "newText"
only in those elements.