我想从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('#'));
注意:我不只是想获取网址 - 我想将其从地址栏中删除。
答案 0 :(得分:6)
history.pushState("", document.title, window.location.href.replace(/\#(.+)/, '').replace(/http(s?)\:\/\/([^\/]+)/, '') )
答案 1 :(得分:0)
尝试此操作:使用.split()
将字符串拆分为#
,然后使用索引0
var url = 'http://example.com#question_1';
var urlWithoutHash = url.split('#')[0];
alert(urlWithoutHash );

答案 2 :(得分:0)
在javascript中使用split
var str = "http://example.com#question_1";
alert(str.split("#")[0]);

答案 3 :(得分:0)
尝试这种方式:
var currentPath = window.location.pathname;
var myUrl = currentPath.split("#")[0];
或强>
var currentPath = window.location.href;
var myUrl = currentPath.split("#")[0];
希望它有所帮助。
答案 4 :(得分:0)
这将清除uri
中的id选择器location.hash = '';
答案 5 :(得分:0)
如图所示使用.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('#'))));