草根站长
老司机 路子野 随时超车
JS获取当前网址是指通过JavaScript代码获取当前网页的URL地址。在前端开发中,获取当前网址是非常常见的需求,比如需要将当前网址作为参数传递给后端接口,或者需要根据当前网址进行一些特定的操作等等。在本文中,我们将介绍一些简单又高效的方法来实现JS获取当前网址。
window.location.href是获取当前网址最简单的方法,它返回的是完整的URL地址,包括协议、域名、端口号和路径等信息。代码如下:
```
let currentUrl = window.location.href;
console.log(currentUrl);
```
document.URL也是获取当前网址的一种常用方法,它与window.location.href的效果相同,返回的是完整的URL地址。代码如下:
```
let currentUrl = document.URL;
console.log(currentUrl);
```
window.location.protocol可以获取当前网页的协议,比如http或https等。代码如下:
```
let currentProtocol = window.location.protocol;
console.log(currentProtocol);
```
window.location.host可以获取当前网页的域名和端口号,不包括协议和路径等信息。代码如下:
```
let currentHost = window.location.host;
console.log(currentHost);
```
window.location.hostn**e可以获取当前网页的域名,不包括端口号、协议和路径等信息。代码如下:
```
let currentHostn**e = window.location.hostn**e;
console.log(currentHostn**e);
```
window.location.pathn**e可以获取当前网页的路径,不包括协议、域名和端口号等信息。代码如下:
```
let currentPathn**e = window.location.pathn**e;
console.log(currentPathn**e);
```
window.location.search可以获取当前网页的查询参数,即URL中问号后面的部分。代码如下:
```
let currentSearch = window.location.search;
console.log(currentSearch);
```
```
let currentHash = window.location.hash;
console.log(currentHash);
```
本文介绍了8种JS获取当前网址的方法,包括window.location.href、document.URL、window.location.protocol、window.location.host、window.location.hostn**e、window.location.pathn**e、window.location.search和window.location.hash。这些方法都非常简单易用,可以根据实际需求选择合适的方法来获取当前网址。
一般声明演示:本文由佚名于2023-05-23 10:48:08发表在小余博客,如有疑问,请联系我们。
本文链接:https://www.yumlamp.com/frontend/2038.html
发表评论