-3

Currently im looping through links in a page and checking if the link contains a string to determine the url. Heres my current code:

$( ".domain a" ).each( function () {

                if ($(this).is(':contains("imgur")')) {

This can detect if the element contains the string "imgur", but because of this is a link goes to a site like slimgur.com, it will also return true.

How can I properly check that the url is, in this example, imgur.com or any of its subdomains (i.imgur.com & m.imgur.com) and that a url such as slimgur.com wont return true?

Orbit
  • 2,985
  • 9
  • 49
  • 106

3 Answers3

2

Rather than check the text, use the properties associated to an <a> tag like hostname.

$( ".domain a" ).filter(function(){
   return this.hostname === 'imgur.com';
}).doSomething();

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

You could do something like: JS Fiddle

$('a').each(function () {
    var url = "yahoo.com";
    var anchor = $(this).attr('href');
    var domain = url_domain(anchor);

    if (url === domain) {
       //Do something here
    }
});

function url_domain(data) {
  var    a      = document.createElement('a');
         a.href = data;
  return a.hostname;
} 

url_domain() function found here: Extract hostname name from string

Community
  • 1
  • 1
Derek Story
  • 9,518
  • 1
  • 24
  • 34
  • would need to know exact url to be able to match, OP seems only interested in domain. Example seems too trivialized – charlietfl Sep 11 '15 at 00:37
  • Yep, it looks like this would only match to a specific url. For example with imgur, image urls have a random string attached to the url so a hardcoded variable wouldnt really work. – Orbit Sep 11 '15 at 00:42
1

This will do it:

$( ".domain a" ).each( function() {
    var str = 'imgur';
    if($(this)[0].hostname.split('.').indexOf(str) > -1) {
       console.log('Found ' + str);
    }       
})
Beroza Paul
  • 2,047
  • 1
  • 16
  • 16
  • What does `$(this)[0]` do? Simply using `this.hostname` seems to work as well. – Orbit Sep 11 '15 at 01:27
  • Inside the loop(each) $(this) is a jQuery object. But hostname works with javascript object. I just made Javascript object from jQuery object using $(this)[0]. So in here $(this)[0] = this – Beroza Paul Sep 11 '15 at 01:35
  • Ah ok. Accepting this as the answer as it programmatically includes all subdomains and seems to be the cleanest solution for my situation. Thanks! – Orbit Sep 11 '15 at 01:39