当前位置:首页 > 开发实践 > 正文

js获取当前网址_如何实现简单又高效的方法

js获取当前网址_如何实现简单又高效的方法


本文目录一览

JS获取当前网址是指通过JavaScript代码获取当前网页的URL地址。在前端开发中,获取当前网址是非常常见的需求,比如需要将当前网址作为参数传递给后端接口,或者需要根据当前网址进行一些特定的操作等等。在本文中,我们将介绍一些简单又高效的方法来实现JS获取当前网址。

方法一:window.location.href

window.location.href是获取当前网址最简单的方法,它返回的是完整的URL地址,包括协议、域名、端口号和路径等信息。代码如下:

```

let currentUrl = window.location.href;

console.log(currentUrl);

```

方法二:document.URL

document.URL也是获取当前网址的一种常用方法,它与window.location.href的效果相同,返回的是完整的URL地址。代码如下:

```

let currentUrl = document.URL;

console.log(currentUrl);

```

方法三:window.location.protocol

window.location.protocol可以获取当前网页的协议,比如http或https等。代码如下:

```

let currentProtocol = window.location.protocol;

console.log(currentProtocol);

```

方法四:window.location.host

window.location.host可以获取当前网页的域名和端口号,不包括协议和路径等信息。代码如下:

```

let currentHost = window.location.host;

console.log(currentHost);

```

方法五:window.location.hostn**e

window.location.hostn**e可以获取当前网页的域名,不包括端口号、协议和路径等信息。代码如下:

```

let currentHostn**e = window.location.hostn**e;

console.log(currentHostn**e);

```

方法六:window.location.pathn**e

window.location.pathn**e可以获取当前网页的路径,不包括协议、域名和端口号等信息。代码如下:

```

let currentPathn**e = window.location.pathn**e;

console.log(currentPathn**e);

```

方法七:window.location.search

window.location.search可以获取当前网页的查询参数,即URL中问号后面的部分。代码如下:

```

let currentSearch = window.location.search;

console.log(currentSearch);

```

方法八:window.location.hash

window.location.hash可以获取当前网页的锚点,即URL中号后面的部分。代码如下:

```

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。这些方法都非常简单易用,可以根据实际需求选择合适的方法来获取当前网址。

发表评论

  • 人参与,条评论

热门阅读

最新文章

取消
扫码支持 支付码