gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:36:33 24 4
gpt4 key购买 nike

如何找到页面上以 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com