JSFiddle - React, Tailwind, and code Playground

by no2don

HTML

<p>
<a target="_blank" href="https://httpbin.org/anything?ref=donma&test=12345">Test already existed</a><br>
</p>

<p>
<a  target="_blank" href="https://httpbin.org/anything?ref=notdonma">Test already existed 2</a><br>
</p>
<p>
<a  target="_blank" href="https://httpbin.org/anything?test=123&ref=notdonma&id=userAAA">Test already existed 3</a><br>
</p>
<p>
<a  target="_blank" href="https://httpbin.org/anything?test=123">Test not existed</a><br>
</p>
<p>
<a  target="_blank" href="https://httpbin.org/anything">TEST with Noting</a><br>
</p>

JavaScript

//pasrse 網址中的 querystring 的值
//sample: ?key=value
//urlParam(url,'key');  //result:value
function urlParam( url,paraKey) {
  var results = new RegExp('[\?&]' + paraKey + '=([^&#]*)').exec(url);
  return results ? decodeURIComponent(results[1].replace(/\+/g, '%20')) : null;
}


//檢查網址的 key 並且取代成新的值,如果沒有則補上
function CheckAndReaplaceNewQS(href, key, newParaValue) {

  var preValue = urlParam(key, href);

  if (preValue != null) {

    href = href.replace('&' + key + '=' + preValue, '');
    href = href.replace(key + '=' + preValue, '');
  }

  if (href.indexOf('?') > -1) {
    href = href + '&' + key + '=' + newParaValue;
  } else {
    href = href + '?' + key + '=' + newParaValue;
  }
  return href;

}



$('a').each(function() {
  var href = $(this).attr('href');
  //將 ref 都換成 donma ,沒有則補上
  var newhref = CheckAndReaplaceNewQS(href, 'ref', 'donma');
	$(this).attr('href',newhref);
});