Using jQuery to check if a link is internal or external

后端 未结 8 938
南旧
南旧 2020-12-29 09:29

I want to write a script which can determine whether a link is internal or external. This is simple from my perspective, all internal links are relative, so they start with

8条回答
  •  猫巷女王i
    2020-12-29 10:16

    You could use the attribute^=value syntax to find hrefs that start with http or /:

    $("a[href^='http']") // external
    
    $("a[href^='/']") // internal
    

    Here's a better solution: You can add $('a:external') and $('a:internal') selectors to jQuery with the plugin code below. Any URL that begins http://, https://, or whatever:// is considered external.

        $.expr[':'].external = function (a) {
            var PATTERN_FOR_EXTERNAL_URLS = /^(\w+:)?\/\//;
            var href = $(a).attr('href');
            return href !== undefined && href.search(PATTERN_FOR_EXTERNAL_URLS) !== -1;
        };
    
        $.expr[':'].internal = function (a) {
            return $(a).attr('href') !== undefined && !$.expr[':'].external(a);
        };
    

提交回复
热议问题