【问题标题】:how to wrap urls with anchor tag and ignore urls that already have anchor tags in jquery如何用锚标记包装url并忽略jquery中已经有锚标记的url
【发布时间】:2014-03-20 16:41:48
【问题描述】:
我有一个简单的替换功能,可以替换像
这样的 url
http://www.example.com to <a href="www.example.com">http://www.example.com</a>
下面给出
text = text.replace(/(\s|>|^)(https?:[^\s<]*)/igm,'$1<a href="$2" class="oembed" >$2</a>');
text = text.replace(/(\s|>|^)(mailto:[^\s<]*)/igm,'$1<a href="$2" class="oembed" target="_blank">$2</a>');
问题是它也将 url 包装在锚标签内,我必须提供 html 作为输入,所以请帮助我使用正则表达式来忽略已经具有锚标签的 url 的包装锚标签
【问题讨论】:
标签:
javascript
jquery
regex
【解决方案1】:
好吧,如果您是一个一个地创建 url 并在创建它们后立即附加到 dom,那么您可以尝试类似
var url = $('a[href="url you are about to create"]');
if(url== undefined)
// url does not exist, create.
else
//already added, ignore
【解决方案2】:
如果您使用的是 jQuery,您可以尝试以下方法,该方法忽略所有元素(包括 a 元素)并包装与正则表达式匹配的 textNodes。
var url = /(http|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/gi;
var mailto = /(mailto:[a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/gi;
str = $('<div>').html(str).contents().each(function () {
if (this.nodeType === 3) { // if node is a textNode
$(this).replaceWith(function () {
return this.nodeValue.replace(url, function (m) {
return '<a href="' + m + '" class="oembed">' + m + '</a>';
}).replace(mailto, function(m) {
return '<a href="' + m + '" class="oembed" target="_blank">' + m + '</a>';
});
})
}
}).end().html();
http://jsfiddle.net/E8V5y/