Automatically add target blank attribute for all external links using jQuery

Last Updated: January 28, 2019

var comp = new RegExp(location.host);
$('a').each(function() {
	
	if (comp.test($(this).attr('href'))) {
	    $(this).addClass('local');
	    $(this).attr('target', '_self');
	} else {
	    var href = $(this).attr('href');
	    if (href.indexOf('mailto') > -1) { //mailto               
	    	console.log("sdfsdf");              
	    	$(this).attr('target','_self');           
	    }else{              
	    	$(this).addClass('external');              
	    	$(this).attr('target','_blank');           
	    }                             
	}    
});

Add your feedback or comment below: