0

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!

3
  • You can get the current url using document.URL and pick the query params. Commented Jul 23, 2019 at 9:24
  • If I understood correctly, you need to get the current page's URL, transform it, and assign it to the link tag? Commented Jul 23, 2019 at 9:24
  • Or possible you need the other page URL(Page B), and put this URL in <a> tag of page(A)? Commented Jul 23, 2019 at 9:26

3 Answers 3

3

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;
Sign up to request clarification or add additional context in comments.

4 Comments

I love template strings :3
Thank you very much! This neatly solves my problem.
@Riven Me too :) especially when most browsers today support ES6: and even if they don't, you can just use a transpiler.
@SinisaBajic Glad my answer helped you :)
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.