cubus
cubus

Reputation: 1

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.

Upvotes: 0

Views: 2904

Answers (4)

cubus
cubus

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

Upvotes: 0

mplungjan
mplungjan

Reputation: 177885

For example

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

Upvotes: 1

Lasse
Lasse

Reputation: 1656

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.

Upvotes: 3

codingrose
codingrose

Reputation: 15699

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.

Upvotes: 1

Related Questions