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);
};
I think the simple and less headaches approach for this is not to use pure javascript or jQuery, but combine it with html instead and then check if the clicked link containing your base site's url. It will work for any type of base url (eg.: example.com, example.com/site). If you need for dynamic value, then you just need to set the value using your preferred server side programming language, such as PHP, asp, java etc.
Here is an example:
HTML
<!--Create a hidden input containing your base site's url.-->
<input type="hidden" id="sitedomain" value="example.com/site"/>
jQuery
$(".elem").on("click", function(e){
if($(this).closest("a").length) {
var url = $(this).attr("href");
var sitedomain = $("#sitedomain").val();
if(url.indexOf(sitedomain) > -1) {
alert("Internal");
} else {
alert("External");
}
}
});