如何使用 JavaScript 获取 URL?使用 window.location.href 获取当前 URL。使用 new URL(window.location.href) 解析 URL,创建包含协议、主机、路径等部分的 URL 对象。使用 URL 对象的属性(如 .pathname)访问特定 URL 部分。修改 URL 对象的属性(如 .pathname)以更新 URL。使用 window.location.href 将修改后的 URL 更新到浏览器窗口中。

如何使用 JavaScript 获取 URL
直接访问 URL
<code class="javascript">const url = window.location.href;</code>
解析 URL
<code class="javascript">const url = new URL(window.location.href);</code>
这会创建一个 URL 对象,包含以下部分:
-
protocol: 协议(如 "http://") -
host: 主机名(如 "example.com") -
port: 端口号(如 80) -
pathname: 路径(如 "/index.html") -
search: 查询字符串(如 "?q=search+term") -
hash: 哈希部分(如 "#section-one")
访问特定 URL 部分
您可以使用以下属性访问特定 URL 部分:
url.protocolurl.hosturl.porturl.pathnameurl.searchurl.hash
修改 URL
可以通过重新分配以下属性来修改 URL:
url.protocolurl.hosturl.porturl.pathnameurl.searchurl.hash
修改 URL 后,您可以使用 window.location.href 将其更新到浏览器窗口中。
示例
获取当前 URL:
<code class="javascript">const currentUrl = window.location.href; // 例如 "https://example.com/index.html"</code>
获取协议:
<code class="javascript">const protocol = new URL(currentUrl).protocol; // 例如 "https:"</code>
更新 URL 的 pathname:
<code class="javascript">const newUrl = new URL(currentUrl); newUrl.pathname = "/new-page.html"; window.location.href = newUrl.href; // 更新浏览器中的 URL</code>










