How to properly switch GET parameters in the address bar via JS?

  • 0
    There was a problem while writing a script that should add a parameter to the beginning or to the end when switching on two links. Two links have one parameter with different values. When you switch and follow the links in the address bar, they begin to be added one after another, like here:

    / products / katalki /? t = 5 & amp; t = 4 & amp; t = 5 & amp; t = 4 & amp; t = 5 & amp; t = 4


    but you need to switch one parameter with

    ? t = 5


    on

    ? t = 4


    and vice versa, and if the parameter comes at the end, then, respectively, at the end. There is a JS code like this:

    var params = window.location.search.replace('?','').split('&').reduce(
            function(p,e){
                var a = e.split('=');
                p[ decodeURIComponent(a[0])] = decodeURIComponent(a[1]);
                return p;
            },
            {}
        );
    
    function addParam(v) {
    	if(params[""] === "undefined") {
    		window.location.search += '?' + v;
    	} else {
    		window.location.search += '&' + v;
    	}
    }


    The links are written in the code:

    <a href="javascript:addParam('t=4');">...</a>
    <a href="javascript:addParam('t=5');">...</a>


    P.S. The link contains other filter parameters such as:

    ? purpose = Manipulation & amp; tabletype = Gynecology & amp; t = 4


    Please help me figure it out
    JavaScript Anonymous, Jul 18, 2020

  • 3 Answers
  • 0
    function updateURLParameter(url, param, paramVal){
    var newAdditionalURL = "";
    var tempArray = url.split("?");
    var baseURL = tempArray[0];
    var additionalURL = tempArray[1];
    var temp = "";
    if (additionalURL) {
    tempArray = additionalURL.split("&");
    for (var i=0; i<tempArray.length; i++){
    if(tempArray[i].split('=')[0] != param){
    newAdditionalURL += temp + tempArray[i];
    temp = "&";
    }
    }
    }

    var rows_txt = temp + "" + param + "=" + paramVal;
    return baseURL + "?" + newAdditionalURL + rows_txt;
    }

    function addParam(v) {
    var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
    newURL = updateURLParameter(newURL, 'resId', 'newResId');

    window.history.replaceState('', '', updateURLParameter(window.location.href, "t", v));
    location.reload();
    }




    HTML



    <a href="javascript:addParam('4');">...</a>
    <a href="javascript:addParam('5');">...</a>




    I decided this way.
    Anonymous

  • 0

  • 0
    /**
    * @param {Object<string, string|number|boolean>} params
    */
    const addParams = params => {
    const url = new URL(location.href);

    for (const key in params) {
    url.searchParams.set(key, params[key]);
    }

    location.href = url;
    };


    Well, it would be nice to replace the links to the buttons.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!