Jacob Kranz
Jacob Kranz

Reputation: 951

get rid of choppiness when doing global regex replacement

Let's pretend that we have a page, say:

<html>
  <body>
    (111) 111.1111
    <br />
    (222) 222.2222
    <br />
    333 333 3333
    <br />
    444-444-4444

    <script>
      // replace all phone numbers with our own

      var re = /\d{3}[().-\s[\]]*\d{3}[().-\s[\]]*\d{4}/g;
      var sourcestring = document.documentElement.innerHTML;
      var replacementpattern = "(111) 867-5309";
      var result = sourcestring.replace(re, replacementpattern);
      document.documentElement.innerHTML = result; 
   </script>                       
  </body>

Our page loads normally but it shows the original phone numbers for maybe 1/4 of a second (highly noticeable).

Is there a way to essentially stop the displaying of other numbers and JUST display the (111) 867-5309 string when replaced?

Maybe a solution is to have something to either parse the html as it comes in (but before it displays)?

EDIT:

Just for clarification, I would not have access to the the rest of the HTML other than the javascript (which would be loaded in via src=)

Upvotes: 0

Views: 45

Answers (1)

Andrew Vermie
Andrew Vermie

Reputation: 633

If you can modify the page enough to move your script, you can make it work.

  1. First, put your script before the content (in the head, preferably).
  2. Your code should be in a function that you can call after the content is ready.
  3. Handle the DOMContentLoaded event with your function. (reference here, with list of fallbacks if it isn't supported by your browser)

Something like this:

<html>
  <head>
    <script>
      function replacePhoneNumbers () {
          // replace all phone numbers with our own

          var re = /\d{3}[().-\s[\]]*\d{3}[().-\s[\]]*\d{4}/g;
          var sourcestring = document.documentElement.innerHTML;
          var replacementpattern = "(111) 867-5309";
          var result = sourcestring.replace(re, replacementpattern);
          document.documentElement.innerHTML = result;
      }

      document.addEventListener('DOMContentLoaded', replacePhoneNumbers);
    </script>
  </head>
  <body>
    ...
  </body>
</html>

If you can't move your script, then there's nothing you can do; it won't be executed until the content is already rendered.

Upvotes: 1

Related Questions