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. When the user's input then passes validation, I need to remove #question_1
from the current location.
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.
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
var url = 'http://example.com#question_1'; var urlWithoutHash = url.split('#')[0]; alert(urlWithoutHash );
Use split
in javascript
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 :
var str = "http://example.com#question_1";
alert((str.split("#")[0]);
or use .substring()
as shown :
var str = "http://example.com#question_1";
alert((str.substring(0,str.indexOf('#'))));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.