Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass/append url parameter to all hrefs (links) on a page?

Using javascript, my objective is to query the URL and append parameters to all links on a page. If the link already contains a parameter, the link will append the new parameters:

User access page:https://example.com/?location=brazil
Link on page was: https://link.com/?hello=ok
Link becomes: https://link.com/?hello=ok&location=brazil

If there’s no previous parameter on link, it becomes:
https://link.com/?location=brazil

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried the following code:

var queryString = new URL(window.location).search;
document.querySelectorAll("[href]").forEach(link => {
    var current = link.href;
    link.href = current + queryString;
});
</script>

But when a link already contains a parameter, it uses ? instead of &
so it becomes:

https://link.com/?hello=ok?location=brazil

How do I solve this problem?

>Solution :

var queryString = new URL(window.location).search;
document.querySelectorAll("[href]").forEach(link => {
    var current = link.href;
    link.href = `${current}${current.includes('?') ? queryString.replace('?', '&') : queryString}`;
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading