Sinisa Bajic
Sinisa Bajic

Reputation: 3

Fetch Query String From URL and Pass It to Href

I saw several possible solutions to my problem here but somehow I fail to find appropriate solution.

My scenario is this:

User comes to pageA carrying query string in url.

It looks like this: http://example.com?name=xxxxx&email=xxxxx&a1=1xxxxx

On that page I have two links, lets say their IDs are linkA and linkB.

I am interested in first one with the markup like this:

<a href="" id="linkA">Link A</a>

I need to fetch entire query string from url and add it to linkA which will point to another URL. So the final link looks like this:

<a href="http://anotherurl.com?name=xxxxx&email=xxxxx&a1=1xxxxx" id="linkA">Link A</a>

Can you help me out with clean solution?

Thank you in advance!

Upvotes: 0

Views: 136

Answers (3)

Raghav Patel
Raghav Patel

Reputation: 843

Try this code, it's working fine:

$(document).ready(function(){
    var parameters = window.location.search;
    var link = $('#linkA').attr('href');
    $('#linkA').attr('href', link + parameters);
});

Upvotes: 0

Tech Pirate
Tech Pirate

Reputation: 1

You could try using search key of window.location which returns the search query of the current url.

So, on http://example.com/?name=xxxxx&email=xxxxx&a1=1xxxxx, using the following

window.location.search

will give you the following string

?name=xxxxx&email=xxxxx&a1=1xxxxx

You could then append this string to the "href" of the second anchor tag

Upvotes: 0

Terry
Terry

Reputation: 66103

You can just use window.location.search to access the entire query string from the page's URL. It will return something like this: ?name=xxxxx&email=xxxxx&a1=1xxxxx.

You can then append that to your anchor element's href attribute, e.g.

document.querySelector('#linkA').href = `http://anotherurl.com/${window.location.search}`;

If you need an ES5-based solution, this will work:

document.querySelector('#linkA').href = 'http://anotherurl.com/' + window.location.search;

Upvotes: 3

Related Questions