如何使用jquery正则表达式替换字符串中的链接和可点击的版本?

时间:2011-12-02 08:13:03

标签: javascript jquery regex twitter

请参阅下面代码中的第8行,注释:

<script>
$(function(){
    $.getJSON('http://twitter.com/status/user_timeline/TWITTER.json?count=1&callback=?',twitterJSON);
    function twitterJSON(data){
        var twitterOut     = '<p>'+data[0].text+'</p><strong>- '+data[0].user.name+'</strong>';
        var twitterOutAt   = twitterOut.replace(/\B@([\w-]+)/gm,'<a href="http://twitter.com/$1">@$1</a>');
        var twitterOutHash = twitterOutAt.replace(/\B#([\w-]+)/gm,'<a href="http://search.twitter.com/search?q=$1">#$1</a>');
        var twitterOutDone = twitterOutHash.replace(/(href="|<a.*?>)?[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g,'<a href="$1">$1</a>'); // not working :(
        $('.twitter').html(twitterOutDone);
    }
});
</script>

非常感谢任何重构代码的帮助!

例如:必须有一种方法可以链接.replace,这样就不必再次分配新的var。我试过var twitterOut.replace().replace()...,但似乎不起作用:(

2 个答案:

答案 0 :(得分:6)

这是我使用的工作功能:

jQuery.fn.urlize = function() {
    if (this.length > 0) {
        this.each(function(i, obj){
            // making links active
            var x = $(obj).html();
            var list = x.match( /\b(http:\/\/|www\.|http:\/\/www\.)[^ <]{2,200}\b/g );
            if (list) {
                for ( i = 0; i < list.length; i++ ) {
                    var prot = list[i].indexOf('http://') === 0 || list[i].indexOf('https://') === 0 ? '' : 'http://';
                    x = x.replace( list[i], "<a target='_blank' href='" + prot + list[i] + "'>"+ list[i] + "</a>" );
                }

            }
            $(obj).html(x);
        });
    }
};

在你的情况下:

$('.twitter').urlize();

答案 1 :(得分:2)

我在这里找到了一个解决方案:https://stackoverflow.com/a/3890175/1076933

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Twitter</title>
</head>
<body id="top">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>

    $(function() {

        $.getJSON("http://twitter.com/status/user_timeline/envato.json?count=1&callback=?", twitterJSON);

        function twitterJSON(data) {
            var twitterOut = data[0].text;
            twitterOut = twitterOut
                .replace(/(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim, '<a href="$1">$1</a>')
                .replace(/\B#([\w-]+)/gm, '<a href="http://search.twitter.com/search?q=$1">#$1</a>')
                .replace(/\B@([\w-]+)/gm, '<a href="http://twitter.com/$1">@$1</a>');
            $("body").html(twitterOut);
        };

    });

</script>
</body>
</html>

感谢 Silver Light ,他的功能也很有魅力!

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Twitter</title>
</head>
<body id="top">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>

    $(function() {

        jQuery.fn.urlize = function() {
            if (this.length > 0) {
                this.each(function(i, obj) {
                    var x = $(obj).html();
                    var list = x.match(/\b(http:\/\/|www\.|http:\/\/www\.)[^ <]{2,200}\b/g);
                    if (list) {
                        for (i = 0; i < list.length; i++) {
                            var prot = list[i].indexOf("http://") === 0 || list[i].indexOf("https://") === 0 ? "" : "http://";
                            x = x.replace(list[i], "<a target='_blank' href='" + prot + list[i] + "'>" + list[i] + "</a>");
                        }
                    }
                    $(obj).html(x);
                })
            }
        };

        $.getJSON("http://twitter.com/status/user_timeline/envato.json?count=1&callback=?", twitterJSON);

        function twitterJSON(data) {
            var twitterOut = data[0].text;
            twitterOut = twitterOut
                .replace(/\B#([\w-]+)/gm, '<a href="http://search.twitter.com/search?q=$1">#$1</a>')
                .replace(/\B@([\w-]+)/gm, '<a href="http://twitter.com/$1">@$1</a>');
            $("body").html(twitterOut).urlize();
        };

    });

</script>
</body>
</html>