问题
I'm searching for a jquery solution that converts the following URL:
http://www.mysite.com/longpage.html#title3
into
http://www.mysite.com/longpage.html?var=1#title3
Simply adding the "?var=1" is no problem. But the anchor only works when it's placed at the end of the URL.
回答1:
From what you're describing in your question, a simple replace will do the trick:
"http://www.mysite.com/longpage.html#title3".replace(/(#.+?)$/, '?var=1$1')
It's just plain JS because that's all that's needed.
回答2:
Try:
var href = window.location.href;
if(href.indexOf("#") > 0){
href = href.split("#")[0] + "?var=1#" + href.split("#")[1];
window.location.href = href;
}
DEMO here.
回答3:
For example
var urlParts = location.href.split("#");;
var newUrl = urlParts[0]+"?var="+someVar+(urlParts.length>1?"#"+urlParts[1]:"");
回答4:
Thanks to you all.
We implemented yet another solution that was suggested:
var url = $(this).attr('href');
var pos = url.indexOf('#');
if (pos != -1) {
var newurl = url.substr(0,pos);
var fragment = url.substr(pos, url.length - pos);
}
else {
var newurl = url;
var fragment = '';
}
$(this).attr('href', newurl + '?var=1' + fragment);
来源:https://stackoverflow.com/questions/20551025/remove-anchor-from-url-add-string-to-url-and-append-anchor-at-the-end-again