如何使用 JavaScript 从 window.location (URL) 中删除哈希值而无需刷新页面?
javascriptobject oriented programmingprogramming
replaceState() 方法使用作为方法参数传递的状态对象、标题和 URL 替换当前历史记录条目。当您想要更新当前历史记录条目的状态对象或 URL 以响应用户操作时,此方法很有用。
要删除哈希 URL,请使用历史记录 API 的 replaceState 方法删除哈希位置。
语法
replaceState() 方法的语法如下 −
window.history.replaceState(stateObj,"unused", "url")
该函数将采用三个参数。它们是 −
stateObj − 此参数与传递给 replace 方法的历史记录条目相关联。此参数可以为空。
URL − 如果新 URL 与当前 URL 不是同一来源,则 ReplaceState 会抛出异常。
示例 1
此示例演示了如何在 JavaScript 中从 URL 中删除哈希值 −
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scal=1.0"> <title>Remove Hash from URL</title> </head> <body style="text-align: align-self: start;"> <h1 style="color: orange">Tutorials Point</h1> <p>Removing the hash from window.location with JavaScript without page refresh </p> <p>modifying the current history state can also be done </p> <button onclick="modState()"> History state Modification </button> <button onclick="remHash()"> Remove hash from url </button> <script> function modState() { let stateObj = { id: "100" }; window.history.replaceState(stateObj, "Untitled-1", "/answer#Untitled-1.html"); } function remHash() { var uri = window.location.toString(); if (uri.indexOf("#") > 0) { var clean_uri = uri.substring(0, uri.indexOf("#")); window.history.replaceState({}, document.title, clean_uri); } } </script> </body> </html>