打开所有<a> links on page that do not have string match in new tab with jquery

时间:2018-07-16 15:25:59

标签: javascript

I need a script that will open up all the href links in new tabs that do NOT contain the query I've specified in the indexOf. This loop does basically exactly the opposite of what I need it to do. I just can't work out how to reverse it's function. Maybe it's right in front of my face and I'm just not seeing it.

So, I am working with this right now.

(function(){
  var links = document.getElementsByTagName('a');
  for (var i=0;i<links.length;i++){
    var href = links[i].href;
    if(href.toLowerCase().indexOf('facebook.com/search') !=-1){
      window.open(links[i].href);
    }
  }
})();

I've tried placing ! and != in this script but it's not working and I'm out of ideas.

1 个答案:

答案 0 :(得分:1)

indexOf在字符串中找不到指定的子字符串时返回-1。现在,您正在打开包含该子字符串的链接。您的if语句应类似于:

if(href.toLowerCase().indexOf('facebook.com/search') == -1)