1

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.

Wasim Shaikh
  • 6,300
  • 18
  • 58
  • 87
  • can you share what you have tried so far? – Code_Ninja Aug 03 '18 at 12:48
  • 2
    Hope this question will help you https://stackoverflow.com/questions/5999118/how-can-i-add-or-update-a-query-string-parameter – Karan Aug 03 '18 at 12:48
  • First get the previous URL by using `document.referrer`, then split it by `=`, then get your desired parameters, then split your current URL by `=`, and then replace the above parameters at desired position. – Code_Ninja Aug 03 '18 at 13:12
  • I didn't knew how to execute the above suggestion in jsfiddle, otherwise I would have provided a working example. – Code_Ninja Aug 03 '18 at 13:13
  • @Karan I have updated answer below. from suggestions , if anyone of you can improve that will be great help. – Wasim Shaikh Aug 06 '18 at 11:19

1 Answers1

0

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.

Wasim Shaikh
  • 6,300
  • 18
  • 58
  • 87