I used the following for a while. I can’t remember where I found it from:
$.expr[':'].external = function(obj){ return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname) && !obj.href.match(/^javascript\:/) && !obj.href.match(/^$/) };
This adds a selector :external jQuery, so you can simply do:
$('a:external').attr('target', '_blank');
The good part about using a custom selector is that if you need to change what constitutes an “external” link, you can change it in one place and not worry about the rest of your code. For example, in my organization we have certain subdomains that are not “external”, but which we still want to open in new windows.
Chris pratt
source share