我试图解析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
还有其他方法可以解析吗?
如果不需要支持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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句