【问题标题】:Remove hash from current page’s URL从当前页面的 URL 中删除哈希
【发布时间】:2014-09-26 10:54:49
【问题描述】:

我想从 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 - 我想从我的地址栏中删除它。

【问题讨论】:

标签: javascript jquery url


【解决方案1】:
history.pushState("", document.title, window.location.href.replace(/\#(.+)/, '').replace(/http(s?)\:\/\/([^\/]+)/, '') )

【讨论】:

    【解决方案2】:

    试试这个:使用.split()# 分割字符串,然后使用索引0 读取数组中的第一个元素

        var url = 'http://example.com#question_1';
        var urlWithoutHash = url.split('#')[0];
        alert(urlWithoutHash );

    【讨论】:

    • 感谢您的回答,但我不想获取 URL,我只想将其从我的 URL 栏中删除
    【解决方案3】:

    在 javascript 中使用split

        var str = "http://example.com#question_1";
        
        alert(str.split("#")[0]);

    【讨论】:

    • 感谢您的回答,但我不想获取网址,我只想从我的网址中删除它
    【解决方案4】:

    试试这个方法:

    var currentPath = window.location.pathname;
    var myUrl = currentPath.split("#")[0];
    

    var currentPath = window.location.href;
    var myUrl = currentPath.split("#")[0];
    

    希望对你有帮助。

    【讨论】:

      【解决方案5】:

      这将从 uri 中清除 id 选择器

      location.hash = '';
      

      【讨论】:

      • 如果不重新加载页面就无法摆脱哈希值,我认为这将是最接近从地址栏中实际删除它的方法:)
      【解决方案6】:

      如图所示使用.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('#'))));
      

      【讨论】:

        猜你喜欢
        • 2016-12-13
        • 2011-05-29
        • 2012-04-19
        • 2012-01-13
        • 1970-01-01
        • 2013-05-15
        • 2013-03-02
        • 1970-01-01
        相关资源
        最近更新 更多