【问题标题】:Regex to make links clickable (in only 'a href' and not 'img src')正则表达式使链接可点击(仅在“a href”而不是“img src”中)
【发布时间】:2015-03-15 00:16:10
【问题描述】:

我一直在努力为某个问题找到一个稳定的解决方案。 我需要将字符串中的所有 http/https 链接设为可点击链接。但只有那些在“a”标签的“href”属性中的链接,而忽略其他所有内容。

我一直在使用这个简单的函数来链接文本 -

  function linkify(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp, "<a target='_blank' href='$1'>$1</a>");
}

但问题是它也将任何“img”标签的“src”属性中的链接转换为可点击链接。这是我不想要的。 我需要链接的字符串可以包含“a”和“img”标签。

我什至参考了这个链接 - How to replace plain URLs with links? 并使用了这个 - https://github.com/cowboy/javascript-linkify,但仍然没有运气。

由于我使用的是 angular.js,我还使用了内置的“linky”过滤器 (https://docs.angularjs.org/api/ngSanitize/filter/linky) 来链接文本,但问题仍然存在。

上述所有解决方案都链接了“a”和“img”标签中的文本。

寻求帮助!谢谢。

【问题讨论】:

  • href属性的值不能点击,因为属性节点没有显示出来。

标签: javascript jquery html regex angularjs


【解决方案1】:

JavaScript 不支持正则表达式中的负向回溯。这是简单的解决方法:

var content = '<a href="http://google.com">Google.com</a> and http://google.com';

var re = /((?:href|src)=")?(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

content = content.replace(re, function (match, attr) {
    if (typeof attr != 'undefined') {
        return match;
    }
    return '<a target="_blank" href="' + match + '">' + match +'</a>';
});

但是您应该避免使用 RegExp 解析 HTML。 Here's why.

【讨论】:

    【解决方案2】:

    您最好的选择是使用 HTML/XML 解析器(Nokogiri for Ruby 对我来说仍然是我的最爱,如果适用的话)来识别和解析“innerHTML”标签内容,您可以在上面运行这样的正则表达式。编程中的一条格言是,您不应该使用正则表达式来解析 XML。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      相关资源
      最近更新 更多