set url parameter(s) from javascript CODE
Usage: set 1 parameter
setUrlParameter({'param_name': 'value1'})
set multiple parameters
setUrlParameter({'param_name': 'value1', 'param_name2': 'value2'})
open the altered url in new tab:
setUrlParameter({'param_name': 'value1'}, true)
get string of updated url instead of redirecting:
let url = setUrlParameter({'param_name': 'value1'}, null, true)
update custom url string instead of using current page url:
setUrlParameter({'param_name': 'value1'}, null, null, 'https://youtube.com')
function setUrlParameter(NameValuePairs, newTab = false, get_string = false, custom_url = false)
{
    let url;
    if(custom_url){
      url = custom_url;
    }else{
      url = window.location.href;
    }
    let hash = location.hash;
    url = url.replace(hash, '');

    for(const ParamNameKey in NameValuePairs){
      if(NameValuePairs.hasOwnProperty(ParamNameKey)){

      
        let paramName = encodeURIComponent(ParamNameKey);
        if (url.indexOf(paramName + "=") >= 0)
        {
            let prefix = url.substring(0, url.indexOf(paramName + "=")); 
            let suffix = url.substring(url.indexOf(paramName + "="));
            suffix = suffix.substring(suffix.indexOf("=") + 1);
            suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
            url = prefix + paramName + "=" + NameValuePairs[ParamNameKey] + suffix;
        }
        else
        {
        if (url.indexOf("?") < 0)
            url += "?" + paramName + "=" + NameValuePairs[ParamNameKey];
        else
            url += "&" + paramName + "=" + NameValuePairs[ParamNameKey];
        }
      }
    }
    if(newTab == true){
      window.open((url + hash), '_blank');
    }else if(get_string === true){
      return (url + hash);
    }else{
      window.location.href = url + hash;
    }
    
}
by გიორგი უზნაძე
4 years ago
JavaScript
URL
1
Pro tip: use ```triple backticks around text``` to write in code fences