How can I add or update a query string parameter?

后端 未结 27 3387
别那么骄傲
别那么骄傲 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:19

    Here's an alternative method using the inbuilt properties of the anchor HTML element:

    • Handles multi-valued parameters.
    • No risk of modifying the # fragment, or anything other than the query string itself.
    • May be a little easier to read? But it is longer.

        var a = document.createElement('a'),
    
    	getHrefWithUpdatedQueryString = function(param, value) {
    	    return updatedQueryString(window.location.href, param, value);
    	},
    
    	updatedQueryString = function(url, param, value) {
    	    /*
    	     A function which modifies the query string 
                 by setting one parameter to a single value.
    
    	     Any other instances of parameter will be removed/replaced.
    	     */
    	    var fragment = encodeURIComponent(param) + 
                               '=' + encodeURIComponent(value);
    
    	    a.href = url;
    
    	    if (a.search.length === 0) {
    		a.search = '?' + fragment;
    	    } else {
    		var didReplace = false,
    		    // Remove leading '?'
    		    parts = a.search.substring(1)
    		// Break into pieces
    			.split('&'),
    
    		    reassemble = [],
    		    len = parts.length;
    
    		for (var i = 0; i < len; i++) {
    		    
    		    var pieces = parts[i].split('=');
    		    if (pieces[0] === param) {
    			if (!didReplace) {
    			    reassemble.push('&' + fragment);
    			    didReplace = true;
    			}
    		    } else {
    			reassemble.push(parts[i]);
    		    }
    		}
    
    		if (!didReplace) {
    		    reassemble.push('&' + fragment);
    		}
    
    		a.search = reassemble.join('&');
    	    }
    
    	    return a.href;
    	};

提交回复
热议问题