简体   繁体   English

从当前页面的网址中删除哈希

[英]Remove hash from current page’s URL

I want to remove the hash, as well as anything after it, from a URL. 我想从网址中删除哈希以及哈希之后的所有内容。 For example, I might have: 例如,我可能有:

http://example.com/#question_1

… which slides to question no. …滑向问题编号。 1 to show an error message. 1以显示错误消息。 When the user's input then passes validation, I need to remove #question_1 from the current location. 当用户输入通过验证后,我需要从当前位置删除#question_1

I've tried all of these, but none of them has worked for me: 我已经尝试了所有这些方法,但是没有一个对我有用:

  • document.location.href.replace(location.hash, "");
  • window.location.hash.split('#')[0];
  • window.location.hash.substr(0, window.location.hash.indexOf('#'));

Note: I don't just want to get the URL – I want to remove it from my address bar. 注意:我不仅要获取URL,还想从地址栏中删除它。

history.pushState("", document.title, window.location.href.replace(/\#(.+)/, '').replace(/http(s?)\:\/\/([^\/]+)/, '') )

Try this :use .split() to split string by # and then read first element in array using index 0 试试这个:使用.split()通过#分割字符串,然后使用索引0读取数组中的第一个元素

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

Use split in javascript 在javascript中使用split

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

Try this way: 尝试这种方式:

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

OR 要么

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

Hope it helps. 希望能帮助到你。

这将从uri中清除ID选择器

location.hash = '';

Use .split as shown : 使用.split ,如下所示:

var str = "http://example.com#question_1";

alert((str.split("#")[0]);

or use .substring() as shown : 或使用.substring() ,如下所示:

var str = "http://example.com#question_1";

alert((str.substring(0,str.indexOf('#'))));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM