[英]Remove hash from URL, load the page at hash-less URL, then add hash to URL without reloading the page
[英]Remove hash from current page’s URL
我想從網址中刪除哈希以及哈希之后的所有內容。 例如,我可能有:
http://example.com/#question_1
…滑向問題編號。 1以顯示錯誤消息。 當用戶輸入通過驗證后,我需要從當前位置刪除#question_1
。
我已經嘗試了所有這些方法,但是沒有一個對我有用:
document.location.href.replace(location.hash, "");
window.location.hash.split('#')[0];
window.location.hash.substr(0, window.location.hash.indexOf('#'));
注意:我不僅要獲取URL,還想從地址欄中刪除它。
history.pushState("", document.title, window.location.href.replace(/\#(.+)/, '').replace(/http(s?)\:\/\/([^\/]+)/, '') )
試試這個:使用.split()
通過#
分割字符串,然后使用索引0
讀取數組中的第一個元素
var url = 'http://example.com#question_1'; var urlWithoutHash = url.split('#')[0]; alert(urlWithoutHash );
在javascript中使用split
var str = "http://example.com#question_1"; alert(str.split("#")[0]);
嘗試這種方式:
var currentPath = window.location.pathname;
var myUrl = currentPath.split("#")[0];
要么
var currentPath = window.location.href;
var myUrl = currentPath.split("#")[0];
希望能幫助到你。
這將從uri中清除ID選擇器
location.hash = '';
使用.split
,如下所示:
var str = "http://example.com#question_1";
alert((str.split("#")[0]);
或使用.substring()
,如下所示:
var str = "http://example.com#question_1";
alert((str.substring(0,str.indexOf('#'))));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.