JavaScript获取当前页面网址信息、路径、地址、网址、本页面、url、window、location、href、protocol、host、port、pathname、search、hash


1、获取整个URL地址

console.log(window.location.href);
// https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#zh/en/%E5%B7%B2%E7%9F%A5

2、获取url协议

console.log(window.location.protocol);
// https:

3、获取url主机

console.log(window.location.host);
// fanyi.baidu.com

4、获取url端口

console.log(window.location.port);
// 返回空字符,如果采用默认的80端口,
// 即使添加了80端口,那么返回值并不是默认的80而是空字符

5、获取url路径,文件地址

console.log(window.location.pathname);
// /translate

6、获取url问号后面的部分

console.log(window.location.search);
// ?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh

7、获取url井号后面的分段

console.log(window.location.hash);
// #zh/en/%E5%B7%B2%E7%9F%A5

猜你喜欢

转载自blog.csdn.net/weixin_51157081/article/details/124848203