简体   繁体   中英

How to update internal links parameters based on current URL using jQuery?

How we can update the internal links of the page if some visits from specific URL.

For Example.

Some Users comes from Facebook and URL is

https://www.example.com/?utm_source=facebook&utm_medium=cpc&utm_campaign=mobile

and I want to update all my particular links to update based on URL, In case of facebook

Original URL

https://www.example.com/cat/i?pid=ABCD&affid=aff1&affExtParam1=para1&affExtParam2=para2

Updated URL after User visit from facebook link

https://www.example.com/cat/i?pid=ABCD&affid=aff1&affExtParam1=facebook&affExtParam2=mobile

Even If It can edit one parameter in URL that will be helpful.

Note: In param1 and param2 can be any text in exiting page.

Thanks for the hints. I have tried and able to replace one URL Parameters. Below is the code.

Combined scripts from different answers and use below code.

 function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
  if( value === undefined ) {
    if (uri.match(re)) {
        return uri.replace(re, '$1$2');
    } else {
        return uri;
    }
  } else {
    if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
    } else {
    var hash =  '';
    if( uri.indexOf('#') !== -1 ){
        hash = uri.replace(/.*#/, '#');
        uri = uri.replace(/#.*/, '');
    }
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";    
    return uri + separator + key + "=" + value + hash;
  }
  }  
}
  $.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null){
       return null;
    }
    else{
       return decodeURI(results[1]) || 0;
    }
}
    var key = "affExtParam2";
    var value = $.urlParam('utm_source'); 
  $('a').each(function(){
    var uri = $(this).attr("href");
  $(this).attr("href" , updateQueryStringParameter( uri, key, value ));
}); 

Not able to test in JS fiddle but working correctly in local, if you guys can further optimize that will be great help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM