我怎样才能替换'?用 '&' 如果 '?'已经存在于 URL 中了吗?

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

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

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

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

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

我正在使用此脚本将我的会员标签附加到 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';  
    }
}

如果 URL 已经包含“?”我如何使用上面的脚本将“&”标记为附属标记的开头?像这样

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

see this image for better understanding

嗯,就像你说的。检查 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';  
    }
}

如果问号 ?,将 ? 替换为 & url 带有附属标签(作为 utm_source 参数的前置字符)已经出现在 url 中 - 使用以下方法与 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=)/, '&');

console.log(_href);