This is in reference to a question I posted last week.
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.
I'm using jQuery and Regex to filter the contents of a page and make the links clickable.
Here is what I've come up with:
var phoneRegex = new RegExp(/([(]?\d{3}[)]?[(\s)?.-]\d{3}[\s.-]\d{4})(?![^<]*>|[^<>]*<\/)/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 = '<a href="tel:' + phonenumber + '">' + match + '</a>';
return link;
});
return newhtml;
});
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: <a href="tel:1234567890">(123) 456-7890</a>
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.
Is there a more efficient way of doing this? Thanks in advance!