Fastest way to detect external URLs

前端 未结 9 1435
孤街浪徒
孤街浪徒 2020-12-02 14:23

What\'s the fastest method to detect if foo=\'http://john.doe\' is an external url (in comparsion to window.location.href)?

9条回答
  •  抹茶落季
    2020-12-02 15:23

    The main problem, is how to parse an URL, and get a host name our of it. It can be done with following way:

    var _getHostname = function(url) {
      var parser = document.createElement('a');
      parser.href = url;
    
      return parser.hostname;
    }
    
    var isExternal = (_getHostname(window.location.href) !== _getHostname('http://john.doe'));
    

    Or you can use is-url-external module.

    var isExternal = require('is-url-external');
    isExternal('http://john.doe'); // true | false 
    

提交回复
热议问题