Test if links are external with jQuery / javascript?

后端 未结 13 1340
囚心锁ツ
囚心锁ツ 2020-11-28 05:00

How do I test to see if links are external or internal? Please note:

  1. I cannot hard code the local domain.
  2. I cannot test for \"http\". I could just as
13条回答
  •  难免孤独
    2020-11-28 05:40

    And the no-jQuery way

    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 beginning with http (http://, https://) are automatically treated as local

提交回复
热议问题