How can I add or update a query string parameter?

后端 未结 27 2885
别那么骄傲
别那么骄傲 2020-11-22 02:35

With javascript how can I add a query string parameter to the url if not present or if it present, update the current value? I am using jquery for my client side development

27条回答
  •  后悔当初
    2020-11-22 03:24

    This should serve the purpose:

    function updateQueryString(url, key, value) {
        var arr =  url.split("#");
        var url = arr[0];
        var fragmentId = arr[1];
        var updatedQS = "";
        if (url.indexOf("?") == -1) {
            updatedQS = encodeURIComponent(key) + "=" + encodeURIComponent(value);
        }
        else {
            updatedQS = addOrModifyQS(url.substring(url.indexOf("?") + 1), key, value); 
        }
        url = url.substring(0, url.indexOf("?")) + "?" + updatedQS;
        if (typeof fragmentId !== 'undefined') {
            url = url + "#" + fragmentId;
        }
        return url;
    }
    
    function addOrModifyQS(queryStrings, key, value) {
        var oldQueryStrings = queryStrings.split("&");
        var newQueryStrings = new Array();
        var isNewKey = true;
        for (var i in oldQueryStrings) {
            var currItem = oldQueryStrings[i];
            var searchKey = key + "=";
            if (currItem.indexOf(searchKey) != -1) {
                currItem = encodeURIComponent(key) + "=" + encodeURIComponent(value);
                isNewKey = false;
            }
            newQueryStrings.push(currItem);
        }
        if (isNewKey) {
            newQueryStrings.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
        }
        return newQueryStrings.join("&");
    }   
    

提交回复
热议问题