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

橙三吉。 提交于 2019-12-22 08:39:19

问题


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.


回答1:


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/




回答2:


You can replace all instances of your phone number with regex

js

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

    text = text.replace(/(phone\-number)/g, "<a href=\"tel:$1\">$1</a>");

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

html

        <div id="departments">
           <ul>
             <li> Department 1 - phone-number</li>
             <li> Department 2 - phone-number</li>
             <li> Department 3 - phone-number</li>
           </ul>
        </div>


来源:https://stackoverflow.com/questions/17901359/jquery-find-phone-numbers-on-page-and-wrap-in-a-href-tel-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!