通过jquery查找和替换用<a>标签包装文本网址

Mat*_*iva 5 javascript regex jquery replace

我正在通过 getJSON 拉入推文,并使用 javascript 将它们写入 Google 地图信息窗口。问题是,这些推文带有文本链接,但没有格式(也没有 ID/类/任何可以缩小查找和替换范围的内容)。这是我现在用来查找文本的代码混搭,但我无法让它包装它在<a>标签中找到的任何内容以正确显示链接:

function wrap( str ) {
    return '<a href="' + str + '">' + str + '<\/a>';
};

function replaceText() {
    var jthis = $(this);
    $("*").each(function () {
        if (jthis.children().length == 0) {
            jthis.text(jthis.text().replace(/\bhttp[^ ]+/i, wrap));
        }
    });
}
$(document).ready(replaceText);
$("html").ajaxStop(replaceText);
Run Code Online (Sandbox Code Playgroud)

我是否忽略了某些东西,或者有没有人知道更好的方法来做到这一点?

Val*_*dis 6

如果我理解你的问题是正确的,这应该有效。不知道为什么要遍历元素,因为 regexp 无论如何都会扫描所有文本。

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
        <script>
        function wrap( str ) {
            return '<a href="' + str + '">' + str + '<\/a>';
        };
        function replaceText() {
            $(".tweet").each( function(){
              $(this).html($(this).html().replace(/\bhttp[^ ]+/ig, wrap));
            })

        }
        $(document).ready(replaceText);
        </script>
    </head>
    <body>
        <div class="tweet"> test 1 http://example.com/path </div>
        <div class="tweet"> test 2 http://example.com/path </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)