当前位置: 动力学知识库 > 问答 > 编程问答 >

jQuery / JavaScript find and replace with RegEx

问题描述:

I have a number of pages that contain phone number in this format xxx-xxx-xxxx.

These phone numbers are not links, what I need to do it write some script that first finds these phone numbers. This is what I have got for that:

$(document).ready(function(){

var content = $(".main").text();

var phoneNumber = content.match(/\d{3}-\d{3}-\d{4}/)

alert(phoneNumber);

});

This works in so much that is captures the number, what I need to do now is replace that phone number on the page with

'<a href=" onclick=" ... "' + 'tel:' + phoneNumber + '">' + 'originalPhoneNumber' + '</a>'

However I am totally lost at this point. Can I use .replaceWith() in jQuery?

EDIT:

Okay I tried to modify the code to include the second attribute i wanted:

$(document).ready(function () {

var content = $(".main").html();

content = content.replace(/\d{3}-\d{3}-\d{4}/g, function(v){

return $('<a>').attr({

href: "tel:"+v,

onclick: "ga('send', 'event', 'lead', 'phone call', 'call');"

}).html(v)[0].outerHTML;

});

$('.main').html(content);

});

It is still adding the href but it is ignoring the onclick.

网友答案:

This will replace all matching strings in an element with a tel: link

<div class = "main">333-333-3333 444-444-4444</div>

<script type="text/javascript">

    var content = $(".main").text();

    content = content.replace(/\d{3}-\d{3}-\d{4}/g, function(v){
        return $('<a>').attr('class', set.classname).attr('href', 'tel:'+v).html(v).wrap('<a>').parent().html();
    });

    $('.main').html(content);

</script>

Or more neatly implemented as :

    $.fn.extend({
        tel : function(def) {

            var set = {
                regex : /\d{3}-\d{3}-\d{4}/g,
                classname : ""
            }

            $.extend(true, set, def);

            var c = $(this).html();

            c = c.replace(set.regex, function(v){
                return $('<a>').attr('class', set.classname).attr('href', 'tel:'+v).html(v).wrap('<a>').parent().html();
            });

            $(this).html(c);
            return this;
        }
    });

    // default regex: 000-000-0000
    $('.main').tel();       

    // default regex: 000-000-0000 <a> class of tel-link applied
    $('.main').tel({ classname : "tel-link" });             

    // override regex: 0000-0000-000    
    $('.main').tel({ regex: /\d{4}-\d{4}-\d{3}/g });
分享给朋友:
您可能感兴趣的文章:
随机阅读: