正则表达式在新窗口中打开主机名中不包含"xyz"的链接,使用 jQuery ?



我需要添加一个jQuery检查,它将启动我的网站上指向外部网站的任何链接。我该如何执行以下操作:

查找主机名中不包含"xyz"的任何锚链接。例如:

  • http://xyz.com
  • http://asfasdfadsfadsf.xyz.com

但是,它必须忽略主机名后包含 xyz 的任何链接:

  • http://someothersite.com/xyz
$('a[href^="http://%xyz%"]').filter(function() {
  return this.hostname && this.hostname !== location.hostname;
}).attr('target', '_blank');  
!(/https?://[^/]*xyz.*/i.test(link))

请参阅此演示


JSHint示例:

/*global $:false */
(function() {
  "use strict";
  $('a').filter(function() {
    return !(/https?://[^/]*xyz.*/i.test($(this).attr('href')));
  }).text("***");
}());
一种方法

是获取所有锚点链接并遍历每个href应用此正则表达式(?:xyz.)。如果正则表达式存在,这意味着 URL 是错误的,请将其他所有内容推送到 and 数组中,然后对它们做任何您想做的事情。

这可能会做到。 您可能可以进行一些优化:

$("a").each(function(idx, link) {
    var href = link.href;
    if (!href) {return;}
    href = href.split("//");
    if (href.length < 2) {return;}
    href = href[1];
    var index = href.indexOf("/");
    if (index > -1) {
        href = href.substring(0, index);
    }
    if (!/bxyzb/g.test(href)) {
        link.target = "_blank";
    }
});

最新更新