I found a script on the habr that searches for all external links:

$('a').each(function() { var a = new RegExp('/' + window.location.host + '/'); if (!a.test(this.href)) { // что-то делаем } }); 

The problem is that he chooses not only external, but also those who simply have an id or a script is registered in href.

Does anyone have a normal script that would look for purely external links? Or what to add to this?

  • just having an id is what kind of links? View of <a id="test" href=""></a> ? So this code only looks at .hash links - it does not look at the item ID. - Regent
  • No, type <a href="#id"> </a> - Vladimir
  • Perhaps, then it is worth adding the http:// or https:// at the beginning of the link to the check. - Regent

1 answer 1

Here is a good example.

 function linkify(inputText) { var pattern = /([-a-zA-Z0-9@:%_\+.~#?&\/\/=]{2,256}\.[az]{2,4}\b(\/?[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)?)/gi; var replacedText = inputText.replace(pattern, '<a href="$1" target="_blank">$1</a>'); return replacedText; } var div = $('div'), txt = div.text(), newTxt; newTxt = linkify(txt); div.html(newTxt); 

For you it can be rewritten for example like this:

 $(function(){ $('a').each(function() { var a = new RegExp('/' + window.location.host + '/'); var e = /([-a-zA-Z0-9@:%_\+.~#?&\/\/=]{2,256}\.[az]{2,4}\b(\/?[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)?)/gi var b = new RegExp(e); if (this.href && b.test(this.href) && !a.test(this.href)) { $(this).css({ "backgroundColor" : "rgba(255, 0, 0, 0.27)", "padding" : "3px", "border" : "1px #f00 dashed", "opacity" : "1 !important", "display" : "inline-block !important" }); } }); }) 

Here there is a selection of all elements of a , which have an attribute href , and this attribute is a url link that leads to another domain.

  • A good example of the choice of external links, an example of a well-done regular season. - rusnasonov