如何从 IE 中的 URL 字符串中获取域名

how to get domain name from URL string in IE

我有一个 AngularJs 过滤器返回给定 URL 字符串的域名。

app.filter('domain', function() {
  return function(input) {
    if (input) {
      // remove www., add http:// in not existed
      input = input.replace(/(www\.)/i, "");
      if (!input.match(/(http\:)|(https\:)/i)) {
        input = 'http://' + input;
      })

      var url = new URL(input);
      return url.hostname;
    }
    return '';
  };
});

问题是因为我不支持 URL() 方法,所以它在 IE 中不起作用。

是的,根据 this document IE 不支持 URL() 接口。但让我们开箱即用!你的过滤器可以写得更短更快速:

app.filter('domain', function() {
  return function(input) {
    if (input) {
      input = input.replace(/(www\.)/i, "");
      if( !input.replace(/(www\.)/i, "") ) {
        input = 'http://' + input;
      }

      var reg = /:\/\/(.[^/]+)/;
      return input.match(reg)[1];
    }
    return '';
  };
});