如何使用锚标记包装URL并忽略已在jquery中具有锚标记的URL [英] how to wrap urls with anchor tag and ignore urls that already have anchor tags in jquery

查看:103
本文介绍了如何使用锚标记包装URL并忽略已在jquery中具有锚标记的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的替换功能,可以将

i have a simple replace function that replaces urls like

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>');

问题在于它将urls包装在锚标签中,我必须将html作为输入帮助我使用正则表达式来忽略已经拥有锚标记的网址的包装锚标记

The problem is that it wraps urls inside anchor tags as well and i have to give html as input so help me out with the regexp to ignore wraping anchor tag for urls already having an anchor tag

推荐答案

如果你使用的是jQuery,你可以尝试以下方法忽略所有元素(包括 a 元素)并包装与正则表达式匹配的textNodes。

If you are using jQuery you can try the following method which ignores all the elements(including a elements) and wraps the textNodes that match the regex.

var url = /(http|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/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/

这篇关于如何使用锚标记包装URL并忽略已在jquery中具有锚标记的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆