在http文本周围包裹<a>标签

Tim*_*Tim 2 javascript regex string jquery

如何找到以http://开头的页面上的每个单词并在其周围换行标签?

我可以使用像正则表达式这样的东西吗?

lsu*_*rez 5

我不同意jQuery可以在这里找到解决方案.当然,您必须使用某些textNode元素属性来解决这些问题,但是在拆分匹配的节点之后将DOM重新组合在一起可以使用jQuery库变得更容易.

以下代码以内联方式记录,以解释所采取的操作.我把它写成了一个jQuery插件,以防你只是想把它带到其他地方.这样,您可以定义要转换URL的元素,或者只需使用$("body")选择器.

(function($) {
    $.fn.anchorTextUrls = function() {
        // Test a text node's contents for URLs and split and rebuild it with an achor
        var testAndTag = function(el) {
            // Test for URLs along whitespace and punctuation boundaries (don't look too hard or you will be consumed)
            var m = el.nodeValue.match(/(https?:\/\/.*?)[.!?;,]?(\s+|"|$)/);

            // If we've found a valid URL, m[1] contains the URL
            if (m) {
                // Clone the text node to hold the "tail end" of the split node
                var tail = $(el).clone()[0];

                // Substring the nodeValue attribute of the text nodes based on the match boundaries
                el.nodeValue = el.nodeValue.substring(0, el.nodeValue.indexOf(m[1]));
                tail.nodeValue = tail.nodeValue.substring(tail.nodeValue.indexOf(m[1]) + m[1].length);

                // Rebuild the DOM inserting the new anchor element between the split text nodes
                $(el).after(tail).after($("<a></a>").attr("href", m[1]).html(m[1]));

                // Recurse on the new tail node to check for more URLs
                testAndTag(tail);
            }

            // Behave like a function
            return false;
        }

        // For each element selected by jQuery
        this.each(function() {
            // Select all descendant nodes of the element and pick out only text nodes
            var textNodes = $(this).add("*", this).contents().filter(function() {
                return this.nodeType == 3
            });


            // Take action on each text node
            $.each(textNodes, function(i, el) {
                testAndTag(el);
            });
        });
    }
}(jQuery));

$("body").anchorTextUrls(); //Sample call
Run Code Online (Sandbox Code Playgroud)

请记住,鉴于我编写此方法来填充textNodes数组,该方法将找到所有后代文本节点,而不仅仅是直接子文本节点.如果您希望它仅替换特定选择器中的文本中的URL,请删除添加所选元素的所有后代的.add("*",this)调用.

这是一个小提琴的例子.