我怎样才能取代'?'用'&'如果'?'已经存在于URL中?

时间:2017-01-17 12:06:41

标签: javascript jquery affiliate

对于会员ID为'xxxx'的会员,跟踪参数为:

  

utm_source = aff_prog&安培; utm_campaign = AFTS&安培; offer_id = 17&安培; aff_id = XXXX

如果网址已包含'?'(例如:www [dot] companyname [dot] com / products / mobiles-mobile-phones?sort = date),则要追加的跟踪参数应为:

  

&安培; utm_source = aff_prog&安培; utm_campaign = AFTS&安培; offer_id = 17&安培; aff_id = XXXX

我正在使用的是此脚本将我的会员标签附加到网址

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

如果网址已包含&#39;?&#39;如何使用我的上述脚本来标记&#39;&amp;&#39;作为会员标签的起点?像这样

  

&安培; utm_source = aff_prog&安培; utm_campaign = AFTS&安培; offer_id = 17&安培; aff_id = 10001

see this image for better understanding

2 个答案:

答案 0 :(得分:1)

好吧,就像你说的那样。检查href是否包含?并在参数列表前面设置相应的字符:

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

答案 1 :(得分:0)

如果问题标记?已经在网址中出现,请将&替换为utm_source以及具有会员标记的网址(作为?参数的前一个字符) - 使用具有String.prototype.replace()函数和特定正则表达式模式的以下方法:

var _href = 'www[dot]companyname[dot]com/products/mobiles-mobile-phones?sort=date?utm_source=aff_prog&utm_campaign=afts&offer_id=17&aff_id=xxxx',
    _href = _href.replace(/(?=.*?\?.*?)\?(utm_source=)/, '&$1');

console.log(_href);