Expand my Community achievements bar.

Alter href dynamically maintaining querystring

Avatar

Level 1

Hi.

 

I'm trying figure out if the below is possible in Target. Any help or guidance very much appreciated. 

 

We have a couple of pages in our site that include links out to a journey and I'm looking to change the href in that link to another different page/journey. However I need to change the link to the journey, not add a test onto the journey itself...

 

Test page: www.testsite.com/home/

 

Current <a> link on that page is :

www.testsite.com/journeyA?param1=abc123

 

We would like to alter that URL in the href to be changed to:

www.testsite.com/journeyB?param1=abc123

 

We can't do a redirect test as the query params are lost in-between the link and the page loading (weird linking system in our codebase).

 

So I need to alter the href itself in the parent page (while also maintaining or replicating the query params).

 

The query params "abc123" is dynamic and changes user to user so can't be hard coded.

 

Any ideas?

 

Thanks

 

@

 

 

 

 

 

 

 

Topics

Topics help categorize Community content and increase your ability to discover relevant content.

1 Reply

Avatar

Community Advisor

Hi @BobbyBo1 ,

The preferred approach, to not break the query string, is to replace it dynamically. Target in itself doesn't support that as such, but it can host a script to do it for you. At least, that's the best i can think of. 

It could look something like this:

document.querySelectorAll('a[href*="journeyA"]').forEach(function(link) {
    let url = new URL(link.href);
    url.pathname = url.pathname.replace('journeyA', 'journeyB'); // Replace "journeyA" in the path
    link.href = url.toString(); // Update the link
});

Note, I've not tested the script. 

 

  • It loops through all <a> tags where the href contains journeyA.
  • The URL object safely manipulates the pathname (journeyA part) without affecting the query string or other parts of the URL.

 

This is how I would be approaching it. I hope it works for you.