Ram*_*feh 6 javascript url parsing angularjs
我试图在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
Run Code Online (Sandbox Code Playgroud)
但是如果这些地方我遇到了问题:
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
Run Code Online (Sandbox Code Playgroud)
还有其他方法可以解析吗?
squ*_*oid 13
资料来源: - 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"
Run Code Online (Sandbox Code Playgroud)
如果您不需要支持Internet Explorer(http://caniuse.com/#feat=url),请使用URL.用hostname而不是host.
> new URL("http://TLVS0015:3000/cti/YTest").hostname
tlvs0015
Run Code Online (Sandbox Code Playgroud)
端口为80.端口80是默认端口,因此它是多余的"".
> new URL("http://ctmwe:80/ReportServer/ReportService2010.asmx").port
""
port = URL.port === "" ? 80 : URL.port
Run Code Online (Sandbox Code Playgroud)
有关更多信息URL(),请参阅MDN API文档.
注意:截至2017年7月,URL Internet Explorer 11不支持:http://caniuse.com/#feat=url