通过JavaScript的location对象,可获取URL中的协议、主机名、端口、锚点、查询参数等信息。

示例

URLhttp://www.akmsg.com/WebDemo/URLParsing.html#top?username=admin&pwd=123456

解析结果: 

属性名称获取的值说明
location.hash #top?username=admin&pwd=123456 URL中的的锚点部分,包含开头的#符号
location.host www.akmsg.com 主机名称和端口
location.hostname www.akmsg.com 主机名称
location.href http://www.akmsg.com/WebDemo/URLParsing.html#top?username=admin&pwd=123456 完整的URL
location.pathname /WebDemo/URLParsing.html 路径部分
location.port   端口
location.protocol http: 协议,最后面会有个':'冒号
location.search   URL的查询部分(从问号 (?) 开始的 URL)
注意:当URL含有锚点时,此处返回空字符。
location.origin http://www.akmsg.com URL的源。返回格式:协议+主机名+端口
location.origin+location.pathname http://www.akmsg.com/WebDemo/URLParsing.html URL的访问地址。返回格式:协议+主机名+端口+路径部分

代码

console.log(
	'location.hash     :' + location.hash     + '\r\n' +
	'location.host     :' + location.host     + '\r\n' +
	'location.hostname :' + location.hostname + '\r\n' +
	'location.href     :' + location.href     + '\r\n' +
	'location.pathname :' + location.pathname + '\r\n' +
	'location.port     :' + location.port     + '\r\n' +
	'location.protocol :' + location.protocol + '\r\n' +
	'location.hash     :' + location.hash     + '\r\n' +
	'location.search   :' + location.search   + '\r\n' +
	'location.origin   :' + location.origin 
)

 

在线示例

地址http://www.akmsg.com/WebDemo/URLParsing.html

 

posted on 2016-11-03 13:24  FangMu  阅读(6637)  评论(0编辑  收藏  举报