I want to write a script which can determine whether a link is internal or external. This is simple from my perspective, all internal links are relative, so they start with a /. All external links start with an http:// - all good so far. However I can't figure out how to do a ':contains()' on anything other than text - how can a search for a string within an attribute?
Once I can do this I'm happy to add target _blank myself, unless you know a better way to do it
I'm using WordPress for my CMS, and so most (if not all) of my internal links start with "http". I found a pretty interesting solution here: http://www.focal55.com/blog/jquery-tutorial-add-class-all-outbound-links-your-site
In case that site is down, it basically boils down to this selector (I modified it a bit):
$( 'a[href^="//"],a[href^="http"]' )
.not( '[href*="' + window.location.hostname + '"]' )
;
Note that this selector will not be the fastest according to the jQuery docs.
You could use the attribute^=value
syntax to find hrefs that start with http
or /
:
$("a[href^='http']") // external
$("a[href^='/']") // internal
Here's a better solution: You can add $('a:external')
and $('a:internal')
selectors to jQuery with the plugin code below. Any URL that begins http://
, https://
, or whatever://
or //
is considered external. All other URLs are considered internal.
$.expr[':'].external = function (a) {
var PATTERN_FOR_EXTERNAL_URLS = /^(\w+:)?\/\//;
var href = $(a).attr('href');
return href !== undefined && href.search(PATTERN_FOR_EXTERNAL_URLS) !== -1;
};
$.expr[':'].internal = function (a) {
return $(a).attr('href') !== undefined && !$.expr[':'].external(a);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With