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
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:// is considered external.
$.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);
};