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
I prefer this selector myself, it protects against false positives for absolute links that point to your site (like those often generated by a CMS system).
var currentDomain = document.location.protocol + '//' + document.location.hostname;
var outboundLinks = 'a[href^="http"]:not([href*="' + currentDomain + '"])';
Here's the use case where this worked for me, for context:
var currentDomain = document.location.protocol + '//' + document.location.hostname;
$('a[href^="http"]:not([href*="' + currentDomain + '"])').on('click', function (e) {
e.preventDefault();
// track GA event for outbound links
if (typeof _gaq == "undefined")
return;
_gaq.push(["_trackEvent", "outbound", this.href, document.location.pathname + document.location.search]);
});