jQuery Linkify插件:无法处理以括号结尾的链接

时间:2011-05-02 15:10:05

标签: jquery regex dom linkify

我正在使用这个很棒的插件:https://github.com/maranomynet/linkify/blob/master/1.0/jquery.linkify-1.0.js

链接文本操纵dom。问题出在这样的链接上:http://en.wikipedia.org/wiki/The_Godfather_(novel

链接将是“http://en.wikipedia.org/wiki/The_Godfather_(novel”

我可以在linkify代码中更改什么来处理括号等?

谢谢!

PS:嘿,似乎Stackoverflow也可以使用它!哈哈;)

编辑:

我刚看到DaringFireball上的帖子,它工作得很好......问题在于像www.google.com这样的简单网址(我认为它与“noProtocolUrl”的第一个正则表达式有关。这就是我的意思我现在得到了:

var noProtocolUrl = /(^|["'(\s]|<)(www\..+?\..+?)((?:[:?]|\.+)?(?:\s|$)|>|[)"',])/g,
    httpOrMailtoUrl = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:(?:[^\s()<>.]+[.]?)+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi,
        linkifier = function (html) {
            return FormatLink(html
                        .replace(noProtocolUrl, '$1<a href="<``>://$2" rel="nofollow external" class="external_link">$2</a>$3')  // NOTE: we escape `"http` as `"<``>` to make sure `httpOrMailtoUrl` below doesn't find it as a false-positive
                        .replace(httpOrMailtoUrl, '<a href="$1" rel="nofollow external" class="external_link">$1</a>')
                        .replace(/"<``>/g, '"http'));  // reinsert `"http`
        },

使用“www.facebook.com”,我得到了这个(使用rel和class属性就像链接旁边的文本一样:

www.facebook.com" rel="nofollow external" class="external_link">www.facebook.com

1 个答案:

答案 0 :(得分:1)

根据我的发现,the regex expression found here(最初由John Gruber of Daring Fireball创建,由naren1012修改)似乎可以解决问题。

要实现,请替换此代码:

 var noProtocolUrl = /(^|["'(\s]|&lt;)(www\..+?\..+?)((?:[:?]|\.+)?(?:\s|$)|&gt;|[)"',])/g,
      httpOrMailtoUrl = /(^|["'(\s]|&lt;)((?:(?:https?|ftp):\/\/|mailto:).+?)((?:[:?]|\.+)?(?:\s|$)|&gt;|[)"',])/g,
      linkifier = function ( html ) {
          return html
                      .replace( noProtocolUrl, '$1<a href="<``>://$2">$2</a>$3' )  // NOTE: we escape `"http` as `"<``>` to make sure `httpOrMailtoUrl` below doesn't find it as a false-positive
                      .replace( httpOrMailtoUrl, '$1<a href="$2">$2</a>$3' )
                      .replace( /"<``>/g, '"http' );  // reinsert `"http`
        },

使用此代码:

 var noProtocolUrl = /(^|["'(\s]|&lt;)(www\..+?\..+?)((?:[:?]|\.+)?(?:\s|$)|&gt;|[)"',])/g,
  httpOrMailtoUrl = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:(?:[^\s()<>.]+[.]?)+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»����]))/gi,
      linkifier = function ( html ) {
          return html
                      .replace( noProtocolUrl, '$1<a href="<``>://$2">$2</a>$3' )  // NOTE: we escape `"http` as `"<``>` to make sure `httpOrMailtoUrl` below doesn't find it as a false-positive
                      .replace(httpOrMailtoUrl, '<a href="$1">$1</a>')
                      .replace( /"<``>/g, '"http' );  // reinsert `"http`
        },