0

I am using the below script to dynamically change links with query parameters. The links are dynamically changed when I click on the button.

example.com/abc?client_id=123

The problem is when a user lands on the site with this URL from Google Ads - example.com/abc?gclid_id=786, and then clicks on the button the URL is dynamically changed to example.com/abc?gclid=786?client_id=123

I want it example.com/abc?gclid=786&client_id=123

Can I modify the existing script if the users come from Google change the parameter to &client_id=123 and when the user comes organically change the script to ?client_id=123

The parameter values are dynamic and they are mapped with cookie values (This is sorted). The main problem is & and ?

<script>

(function () {


var links = document.querySelectorAll('a[href*=abc]');
  
var clientId = '?client_id={{Read Cookie Value}}'

links.forEach(function(link) {
              
var original = link.getAttribute('href');
link.setAttribute('href', original+clientId)
              
              
              
 })


}) ();
  
</script>
Arif Ahmed
  • 119
  • 1
  • 1
  • 7
  • Instead of concatenating query parameters manually, please use the [`URL` API](//developer.mozilla.org/en/docs/Web/API/URL) and its `searchParams` property, which also [_correctly encodes_ parameters](/q/486896/4642212): `const url = new URL(link.getAttribute('href')); url.searchParams.set("client_id", cookieValue); link.href = url;`. – Sebastian Simon Dec 09 '22 at 13:52
  • I am looking for answers to ```&``` and ```?``` dynamic changes. – Arif Ahmed Dec 09 '22 at 13:55
  • Yes, that’s what the `URL` and `URLSearchParams` API does automatically. Have you tried it already? – Sebastian Simon Dec 09 '22 at 13:56
  • So you are saying when a user lands on the site from Google Ads, the GLCLID parameter will be added. Then when the user clicks on the button, my script will add '&' to click_id instead of '?' – Arif Ahmed Dec 09 '22 at 14:00
  • The question content was quite different. Not sure why this is duplicate. – Arif Ahmed Dec 09 '22 at 14:06
  • 1
    The code in my comment literally provides the solution. You could also simply read the [documentation](//developer.mozilla.org/en/docs/Web/API/URLSearchParams/set). The linked question explains exactly how URL parameters are added. – Sebastian Simon Dec 09 '22 at 14:12
  • Ok thank you. I am not a JavaScript expert, so have difficulty in understanding. – Arif Ahmed Dec 09 '22 at 14:20
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/250289/discussion-between-arif-ahmed-and-sebastian-simon). – Arif Ahmed Dec 09 '22 at 15:15

0 Answers0