Skip to content

Instantly share code, notes, and snippets.

@NikhilMath
Last active March 28, 2023 17:31
Show Gist options
  • Save NikhilMath/44233b40061b3c0fc5f45c7cfd3fa7a6 to your computer and use it in GitHub Desktop.
Save NikhilMath/44233b40061b3c0fc5f45c7cfd3fa7a6 to your computer and use it in GitHub Desktop.
Replace Old Text with New Text with JS

How to replace bad text on a website's DOM with text you want with JS

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment