热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在javascript或angularjs中解析url

如何解决《在javascript或angularjs中解析url》经验,为你挑选了2个好方法。

我试图在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中不受支持.
推荐阅读
author-avatar
大胡子姐姐爱油面巾塞肉
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有