1.获取整个地址栏地址
//获取整个地址栏地址 var href = window.location.href; console.log(href);
以上代码就是获取整个url地址
2.获取url协议部分
//获取url协议部分 var protocol = window.location.protocol; console.log(protocol);
如果url为,则window.location.protocol就是http:
3.获取主机部分
//获取主机部分(带端口号) var host = window.location.host; console.log(host);
如果url为,或者url地址为:1111/test/test.html,则window.location.host为192.1.1.1:1111如果有端口号,端口号也是要带上的
//获取主机部分(不带端口号) var hostname = window.location.hostname; console.log(hostname);
url地址为:1111/test/test.html,则hostname为192.1.1.1
4.获取端口号
//获取端口号 var port = window.location.port; console.log(port);
url地址为:1111/test/test.html,则window.location.port为1111
5.获取url部分路径
//获取部分路径 var pathname = window.location.pathname; console.log(pathname);
url地址为:1111/test/test.html?a=1,则window.location.pathname为/test/test.html,也就是主机部分后面到参数部分前面的就是pathname
6.获取url参数部分
//参数部分 var search = window.location.search; console.log(search);
url地址为:1111/test/test.html?a=1&b=2,则search值为?a=1&b=2
7.获取锚点
//获取锚点 var hash = window.location.hash; console.log(hash);
url地址为:1111/test/test.html?a=1&b=2#1,则hash为#1