[JS] Check if URL is an internal site link


#1

Hey guys,

I already googled for it, but I can only find a solution how to get all internal urls of a site, but lets say the internal url refers to a .jpg and not to an internal site, how could I check that with js?

Thx


#2

Didn’t test it but should work:

var allLinks = document.links, jpglinks;
for (var i=0; i<allLinks.length; i++) {
  if(/\.jpg$/.test(allLinks[i].href) jpglink[] = allLinks[i].href;
}
alert(jpglinks);

#3

Yes for images, but it was only an example. I mean any other file extensions too, so in other words, give me all internal links that refers to an internal site and not to a file, like jpg, mp3, zip, pdf etc.


#4

A HTML file is also a file but I guess this shouldn’t be in your list. If all of your inline links end with a slash you can do

var allLinks = document.links, inlinelinks;
for (var i=0; i<allLinks.length; i++) {
  if(/\/$/.test(allLinks[i].href) inlinelinks[] = allLinks[i].href;
}
alert(inlinelinks);

but I guess you have others as well. I think the only way is to blacklist extensions:

var allLinks = document.links, files;
for (var i=0; i<allLinks.length; i++) {
  if(/\.(jpg|gif|png|mp3|zip|pdf)$/.test(allLinks[i].href) files[] = allLinks[i].href;
}
alert(files);

#5
var url = document.URL;
var base = url.substring(0, url.lastIndexOf("/"));

var a = /http/;
var b = new RegExp(base);

var i = links.length; // "links" array already populated

while(i--) {

	if(links[i].match(b)) {
	
		console.log("link is internal");
		
	}
	else if(links[i].match(a)) {
	
		console.log("links is external");
		
	}
	else {
	
		console.log("link is internal");
		
	}
	
}

#6

@CJ

thats nice , good work.