new URL(window.location.href)
时间: 2023-12-07 22:40:02 浏览: 149
`new URL(window.location.href)`是一个JavaScript语法,用于创建一个URL对象,该对象表示当前页面的URL。它可以用于获取当前页面的各种信息,例如协议、主机名、端口、路径、查询参数等。以下是一个例子:
```javascript
// 获取当前页面的协议
console.log(new URL(window.location.href).protocol); // 输出:http
// 获取当前页面的主机名
console.log(new URL(window.location.href).hostname); // 输出:domain.com
// 获取当前页面的路径
console.log(new URL(window.location.href).pathname); // 输出:/path/to/page
// 获取当前页面的查询参数
console.log(new URL(window.location.href).searchParams.get('topic')); // 输出:api
```
相关问题
new URL(window.location.href).origin
`new URL(window.location.href).origin`是一个JavaScript语法,用于获取当前页面的源(origin),即协议(protocol)、主机(hostname)和端口(port)的组合。这个语法会返回一个字符串,例如`https://www.example.com:8080`。在这个例子中,协议是`https`,主机是`www.example.com`,端口是`8080`。这个语法可以用于获取当前页面的源,也可以用于获取其他URL的源。
window.location.href
This is a property of the window object in JavaScript that returns the URL of the current page. It can also be used to redirect the browser to a new URL by assigning a new value to it. For example, if you wanted to redirect the user to a new page, you could use:
window.location.href = "http://www.example.com/newpage.html";
This would cause the browser to navigate to the new page specified in the URL.
阅读全文