Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find phone numbers on page and wrap in <a href="tel: "> links

This a similar question to this old one that never got answered: Wrap <a> tag around phone number using jquery

I am making a simple jQuery mobile site out of an existing site that uses a custom CMS. In the CMS there are entries that contain code and text like

<div id="departments">
   <ul>
     <li> Department 1 - (555) 123-1234</li>
     <li> Department 2 - (555) 123-4321</li>
     <li> Department 3 - (555) 123-6789</li>
   </ul>
</div>

I know that most mobile phone browsers will automatically convert the phone numbers to clickable links that launch the dialer with the phone number ready to go. However, not all do and I'd like to be able to use jQuery to turn the above into:

<div id="departments">
       <ul>
         <li> Department 1 - <a href="tel:5551231234">(555) 123-1234</a></li>
         <li> Department 2 - <a href="tel:5551234321">(555) 123-4321</a></li>
         <li> Department 3 - <a href="tel:5551236789">(555) 123-6789</a></li>
       </ul>
</div>

I understand the steps to produce this involve using RegEx to match a phone number pattern.

Any ideas? I feel like this would be a helpful plugin to write for lot of people.

UPDATE

Here is what I've tried using the answer and comments below:

var regex = ((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4};

var text = $("body:first").html();

text = text.replace(regex, "<a href=\"tel:$1\">$1</a>");

$("body:first").html(text);

fiddle: http://jsfiddle.net/PShYy/

I can tell that the pattern should work by using: http://gskinner.com/RegExr/?35o5p

I believe it is now a matter of how to correctly do a find and replace in jQuery with regex. I'll continue to research but if anyone wants to chime in. I'd appreciate it.

like image 411
Erik Berger Avatar asked Mar 23 '23 00:03

Erik Berger


1 Answers

Using John's answer as a base I got it to work with:

var regex = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/g; 

var text = $("body:first").html();

text = text.replace(regex, "<a href=\"tel:$&\">$&</a>");

$("body:first").html(text);

Demo: http://jsfiddle.net/PShYy/2/

like image 105
Erik Berger Avatar answered Apr 25 '23 15:04

Erik Berger