简体   繁体   中英

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

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.

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.

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.

For example

var urlParts = location.href.split("#");;
var newUrl = urlParts[0]+"?var="+someVar+(urlParts.length>1?"#"+urlParts[1]:"");

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);

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.

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