Search code examples
javascriptjqueryaffiliate

How can i replace '?' with '&' if '?' is already there in the URL?


For an affiliate with affiliate ID ‘xxxx’, the tracking parameters are:

?utm_source=aff_prog&utm_campaign=afts&offer_id=17&aff_id=xxxx

If the URL already contains a ‘?’ (Example: www[dot]companyname[dot]com/products/mobiles-mobile-phones?sort=date), the tracking parameter to be appended should be:

&utm_source=aff_prog&utm_campaign=afts&offer_id=17&aff_id=xxxx

what I am using is this script to append my affiliate tag to the URL

var links = document.getElementsByTagName('a');


for (var i = 0, max = links.length; i < max; i++) {
    var _href = links[i].href;

    if (_href.indexOf('amazon.in') !== -1) {
    links[i].href = _href + '?&tag=geek-21';  
    }
    else if (_href.indexOf('snapdeal.com') !== -1) {
    links[i].href = _href + '?utm_source=aff_prog&utm_campaign=afts&offer_id=17&aff_id=10001';  
    }
}

if the URL already contains '?' how can I use my above script to tag the '&' as a starting of affiliate tag? like this

&utm_source=aff_prog&utm_campaign=afts&offer_id=17&aff_id=10001

see this image for better understanding


Solution

  • Well, just like you said. Check if the href contains ? and set the appropriate charcter in front of you parameter list:

    for (var i = 0, max = links.length; i < max; i++) {
        var _href = links[i].href;
    
        // this is how to check and set for the appropriate starting character of your parameter list
        var startChar = _href.indexOf("?") === -1 ? "?" : "&";        
    
        if (_href.indexOf('amazon.in') !== -1) {
            links[i].href = _href + startChar +'tag=geek-21';  
        }
        else if (_href.indexOf('snapdeal.com') !== -1) {
            links[i].href = _href + startChar + 'utm_source=aff_prog&utm_campaign=afts&offer_id=17&aff_id=10001';  
        }
    }