在JavaScript或AngularJS中解析URL

6

我正在尝试使用JavaScript解析URL,我找到了以下方法:

var getLocation = function(href) {
    var l = document.createElement("a");
    l.href = href;
    return l;
};
var l = getLocation("http://example.com:3000/path");
var host = l.host; // example.com
var port = l.port; // 3000

但是我在这些位置遇到了问题:

http://TLVS0015:3000/cti/YTest // the parse found the port, but its not found the host

http://ctmwe:80/ReportServer/ReportService2010.asmx // the parse found the host, but don't found the port

有没有其他方法来进行解析?

尝试执行 l.hostname - aug
http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ - smarber
如果您已经有了URL,那么使用split()并获取组件会比创建对象更好,这种做法是否存在性能优势而不是使用字符串? - atmd
2个回答

14

来源:- https://gist.github.com/jlong/2428561

var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

8
如果不需要支持Internet Explorer (http://caniuse.com/#feat=url),请使用URL。使用hostname替换host
> new URL("http://TLVS0015:3000/cti/YTest").hostname
tlvs0015

端口是80。端口80是默认值,因此它是冗余的,因此为""
> new URL("http://ctmwe:80/ReportServer/ReportService2010.asmx").port
""

port = URL.port === "" ? 80 : URL.port

了解更多关于 URL() 的信息,请参阅 MDN API 文档

注意:截至 2017 年 7 月,Internet Explorer 11 不支持 URLhttp://caniuse.com/#feat=url


10
请注意,URL 是一个实验性质的功能,在截至2015年4月的时候不受Internet Explorer支持。 - Adam C
截至2016年7月,它仍然是如此。 - Ian Clark
2017年3月 - 看起来它从未在IE中得到支持,但它在Edge 14和15中得到了支持。http://caniuse.com/#feat=url - Jeremy Wadhams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接