2

我正在使用这个很棒的插件: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 上看到了帖子,效果很好......问题出在简单的 URL 上,比如 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
4

1 回答 1

1

根据我的发现,在这里找到的正则表达式(最初由Daring Fireball 的 John Gruber创建,由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`
        },
于 2011-05-09T21:36:12.000 回答