Remove anchor from url - add string to url - and append anchor at the end again

笑着哭i 提交于 2021-01-29 10:50:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!