作者:大胡子姐姐爱油面巾塞肉 | 来源:互联网 | 2023-05-26 19:45
我试图在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
还有其他方法可以解析吗?
1> squiroid..:
资料来源: - 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"
2> Bas Dirks..:
如果您不需要支持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月,URL
Internet Explorer 11不支持:http://caniuse.com/#feat=url
请注意,`URL`是一个实验性功能,自2015年4月起在Internet Explorer中不受支持.