Check if links are external with jQuery / javascript?

How to check if links are external or internal? Note:

  • I cannot hardcode the local domain.
  • I can not check the "http". I could just as easily link to my own site with an absolute http link.
  • I want to use jQuery / javascript, not css.

I suspect the answer lies somewhere in location.href, but the solution evades me.

Thank!

+49
javascript jquery href location
May 26 '10 at 7:37 a.m.
source share
10 answers
var comp = new RegExp(location.host); $('a').each(function(){ if(comp.test($(this).attr('href'))){ // a link that contains the current host $(this).addClass('local'); } else{ // a link that does not contain the current host $(this).addClass('external'); } }); 

Note. This is just a quick and dirty example. It will match all href = "# anchor" links as external too. This can be improved by doing additional RegExp validation.




Update 2016-11-17

This issue still received a lot of traffic, and many people said that this decision would fail several times. As I said, it was a very quick and dirty answer to show the main way to solve this problem. A more complex solution is to use the properties available for the <a> (anchor) element. Like @Daved already mentioned in this answer, the key should compare hostname with current window.location.hostname . I would rather compare the properties of the hostname , because they never include the port , which is included in the host property, if it is other than 80.

So, let's go:

 $( 'a' ).each(function() { if( location.hostname === this.hostname || !this.hostname.length ) { $(this).addClass('local'); } else { $(this).addClass('external'); } }); 

The prior art:

 Array.from( document.querySelectorAll( 'a' ) ).forEach( a => { a.classList.add( location.hostname === a.hostname || !a.hostname.length ? 'local' : 'external' ); }); 
+32
May 26 '10 at 7:55 a.m.
source share

I know this post is old, but it still appears at the top of the results, so I wanted to suggest a different approach. I see all the regular expression checks on the binding element, but why not just use window.location.host and check the element host property?

 function link_is_external(link_element) { return (link_element.host !== window.location.host); } 

Using jQuery:

 $('a').each(function() { if (link_is_external(this)) { // External } }); 

and with simple javascript:

 var links = document.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { if (link_is_external(links[i])) { // External } } 
+48
Sep 06 '13 at 15:09
source share

And the no-jQuery path

 var nodes = document.getElementsByTagName("a"), i = nodes.length; var regExp = new RegExp("//" + location.host + "($|/)"); while(i--){ var href = nodes[i].href; var isLocal = (href.substring(0,4) === "http") ? regExp.test(href) : true; alert(href + " is " + (isLocal ? "local" : "not local")); } 

All hrefs not starting with http (http: //, https: //) are automatically treated as local

+35
May 26 '10 at 8:18
source share

Here's the jQuery selector for only external links:

 $('a[href^="(http:|https:)?//"])') 

The jQuery selector for internal links only (not including hash links on the same page) should be a little more complicated:

 $('a:not([href^="(http:|https:)?//"],[href^="#"],[href^="mailto:"])') 

Additional filters can be placed in the :not() state and separated by additional commas as needed.

http://jsfiddle.net/mblase75/Pavg2/




Alternatively, we can filter the internal links using the vanilla JavaScript href property, which is always an absolute URL:

 $('a').filter( function(i,el) { return el.href.indexOf(location.protocol+'//'+location.hostname)===0; }) 

http://jsfiddle.net/mblase75/7z6EV/

+7
Jun 06 '14 at 15:09
source share
 var external = RegExp('^((f|ht)tps?:)?//(?!' + location.host + ')'); 

Using:

 external.test('some url'); // => true or false 
+6
May 26 '10 at 8:28
source share

You forgot that if you use a relative path.

forexample: / test

  hostname = new RegExp(location.host); // Act on each link $('a').each(function(){ // Store current link url var url = $(this).attr("href"); // Test if current host (domain) is in it if(hostname.test(url)){ // If it local... $(this).addClass('local'); } else if(url.slice(0, 1) == "/"){ $(this).addClass('local'); } else if(url.slice(0, 1) == "#"){ // It an anchor link $(this).addClass('anchor'); } else { // a link that does not contain the current host $(this).addClass('external'); } }); 

There is also the problem of loading .zip files (local en external), which can use the local load or external load classes. But so far I have not found a solution for this.

+6
Nov 06
source share

You can use the is-url-external module.

 var isExternal = require('is-url-external'); isExternal('http://stackoverflow.com/questions/2910946'); // true | false 
+1
Dec 19 '16 at 14:32
source share

Yes, I believe that you can get the current domain name using location.href. Another possibility is to create a link element, set src to /, and then get the canonical URL (this will extract the base URL if you use it, and not necessarily the domain name).

Also see this entry: Get the full URI from the href property of a link

0
May 26 '10 at 7:42 a.m.
source share

For those who are interested, I made a triple version of the if block with a check to find out which classes the element has and which class is bound.

 $(document).ready(function () { $("a").click(function (e) { var hostname = new RegExp(location.host); var url = $(this).attr("href"); hostname.test(url) ? $(this).addClass('local') : url.slice(0, 1) == "/" && url.slice(-1) == "/" ? $(this).addClass('localpage') : url.slice(0, 1) == "#" ? $(this).addClass('anchor') : $(this).addClass('external'); var classes = $(this).attr("class"); console.log("Link classes: " + classes); $(this).hasClass("external") ? googleAnalytics(url) : $(this).hasClass("anchor") ? console.log("Handle anchor") : console.log("Handle local"); }); }); 

The Google Analytics bit can be ignored, but this is where you probably would like to do something with the URL to find out what type of link it has. Just add the code inside the triple block. If you want to check only 1 type of link, replace tees with an if statement instead.

Edited to add a problem that I encountered. Some of my hrefs were "/ Courses /". I checked the local page, which checks if there is a slash at the beginning and end of the href. Although, probably, it is enough to check for the presence of "/" at the beginning.

0
Mar 23 '16 at 10:48
source share

I use this function for jQuery:

 $.fn.isExternal = function() { var host = window.location.host; var link = $('<a>', { href: this.attr('href') })[0].hostname; return (link !== host); }; 

Usage: $('a').isExternal();

Example: https://codepen.io/allurewebsolutions/pen/ygJPgV

0
03 Oct '17 at 22:22
source share



All Articles