title: Javascript - Replace all phone numbers not already in links to 'click to call' links
body: <p>This is in reference to a <a href="https://stackoverflow.com/questions/34322418/use-regex-to-find-a-phone-number-on-a-page-not-in-an-anchor/34325109#34325109">question</a> I posted last week. </p>
  
  <p>I want to look for all valid phone numbers on a page. If they are not already in a link, I want to create a 'click to call' link to be used on mobile browsers. 
  I received a couple of good answers on the original question I posted, but wanted to try a different approach/expand on the feedback. </p>
  
  <p>I'm using jQuery and Regex to filter the contents of a page and make the links clickable. </p>
  
  <p>Here is what I've come up with: </p>
  
  <pre><code>    var phoneRegex = new RegExp(/([(]?\d{3}[)]?[(\s)?.-]\d{3}[\s.-]\d{4})(?![^&lt;]*&gt;|[^&lt;&gt;]*&lt;\/)/g);
      var phoneNums = $( "body *" ).filter(function() {
      var tagname = $(this).prop("tagName");
      tagname = tagname === null ? "" : tagname.toLowerCase(); 
      if (tagname == "a") { 
          return false;
      }
      var match = $(this).html().match(phoneRegex);
      if (match === null || match.length === 0) {
          return false;
      }
      return true;
  });
  phoneNums.html(function() {
      var newhtml = $(this).html().replace(phoneRegex, function(match) {
          var phonenumber = match.replace(/ /g, "").replace(/-/g, "").replace(/\(/g, "").replace(/\)/g, "");
          var link = '&lt;a href="tel:' + phonenumber + '"&gt;' + match + '&lt;/a&gt;';
          return link;
      });
      return newhtml;
  });
  </code></pre>
  
  <p>So, basically I search for everything in the body looking for each tag (excluding anchor tags). I'm matching the regex and storing the values in the 'phoneNums' variable. 
  From there I remove all spaces, dashes, and parenthesis so the number will format correctly for the tel attribute. 
  So a number such as this: (123) 456-7890 will format like this: <code>&lt;a href="tel:1234567890"&gt;(123) 456-7890&lt;/a&gt;</code></p>
  
  <p>The problem I see with doing this is if these numbers are in nested tags on the page, I'm getting the results multiple times. (This can be seen if you do a console.log on link, just before it is returned.) The results are correct, but wondering if this makes sense. </p>
  
  <p>Is there a more efficient way of doing this? Thanks in advance!  </p>