Kenny Lajara Kenny Lajara - 6 months ago 23
jQuery Question

JQuery selector for domain list

I have a function in my code that I need to modify links in my page, it looks something like this:

$('a').each(function(){
// code here related to HREF attr
});
$('form').each(function(){
// Code relate to the TARGET attr
});


I need to apply this function on all the links and targets of forms pointing to some specific domains. Let's say I have a list like this one:
www.example.com,www.domain.com,www.anotherdomain.com


How can I modify the selector in a way it could apply it only to links and form pionting to the domains in the list?

Answer

You can use new RegExp() with parameter array list joined with delimiter "|", RegExp.prototype.test()

var list = ["www.example.com","www.domain.com","www.anotherdomain.com"];

$("a, form").each(function(i, el) {
  if (new RegExp(list.join("|")).test(this.href || this.target)) {
    // do stuff
  }
})

jsfiddle https://jsfiddle.net/xkjpxd6L/