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

标签 javascript jquery regex string

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

我可以使用正则表达式之类的东西吗?

最佳答案

我非常不同意 jQuery 在寻找解决方案方面有很大用处。当然,您必须认真处理一些 textNode 元素属性,但是使用 jQuery 库,在分割匹配的节点后将 DOM 重新组合在一起可以变得更容易一些。

以下代码内联记录以解释所采取的操作。我已将其编写为 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

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

这是一个fiddle example .

关于javascript - 将 <a> 标签包裹在 http 文本周围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5158022/

相关文章:

jquery - 使用jquery动态添加文本框

javascript - 在Python中匹配Javascript转义表单数据

Javascript 在 Internet Explorer 中破坏属性的空值 - 如何让 IE 忽略此问题?

php - 所需 php 中的 Javascript 文件不起作用,但直接在文件中可以

jquery - 单击子元素会触发父元素单击事件

javascript - 观察新 DOM 节点的插入并调用它们的方法

javascript - 迭代对象数组并更新属性

javascript - 在 windows 8 html5 的挂起状态事件处理程序中写入文本文件

javascript - 正则表达式接受从 0 到 168 的所有小数,后跟 N 或 S

javascript - 什么是javascript正则表达式来验证字符串值数组