Recently, I had to perform a similar problem, and I came up with something similar to this:
<!DOCTYPE html> <html> <head> <title>HTML JS REPLACE</title> <script type="text/javascript"> function convert(elem) { var content = document.getElementById(elem).innerHTML; </script> </head> <body> <div id="content"> Some text that includes both hello and hi. And a hello. </div> <script type="text/javascript"> window.onload = convert('content'); </script> </body> </html>
As a result, you will receive a page with the message:
Some texts containing both hello and hello. And hi.
while the original source still says:
Some text that includes both hello and hello. And hi.
Complicated bits are just a few - first, you want the window.onload trigger to turn on at the bottom of the body, so the DOM loads completely before running JS on it. Secondly, you must have a top-level element to which you assign a unique identifier that you can reference in JS. Third, the conversion function uses a regular expression that performs a global case-insensitive replacement for the string "hello", changing it to "hello."
In your specific application, you may need to instead capture all occurrences and then analyze them in a loop, which may (or may not) cause some performance issues. Be careful:)
source share