How can I add or update a query string parameter?

后端 未结 27 2838
别那么骄傲
别那么骄傲 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;
    	};

    0 讨论(0)
  • 2020-11-22 03:21

    Here is my library to do that: https://github.com/Mikhus/jsurl

    var u = new Url;
    u.query.param='value'; // adds or replaces the param
    alert(u)
    
    0 讨论(0)
  • 2020-11-22 03:22

    Based on the answer @ellemayo gave, I came up with the following solution that allows for disabling of the hash tag if desired:

    function updateQueryString(key, value, options) {
        if (!options) options = {};
    
        var url = options.url || location.href;
        var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"), hash;
    
        hash = url.split('#');
        url = hash[0];
        if (re.test(url)) {
            if (typeof value !== 'undefined' && value !== null) {
                url = url.replace(re, '$1' + key + "=" + value + '$2$3');
            } else {
                url = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
            }
        } else if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            url = url + separator + key + '=' + value;
        }
    
        if ((typeof options.hash === 'undefined' || options.hash) &&
            typeof hash[1] !== 'undefined' && hash[1] !== null)
            url += '#' + hash[1];
        return url;
    }
    

    Call it like this:

    updateQueryString('foo', 'bar', {
        url: 'http://my.example.com#hash',
        hash: false
    });
    

    Results in:

    http://my.example.com?foo=bar
    
    0 讨论(0)
  • 2020-11-22 03:22

    To give an code example for modifying window.location.search as suggested by Gal and tradyblix:

    var qs = window.location.search || "?";
    var param = key + "=" + value; // remember to URI encode your parameters
    if (qs.length > 1) {
        // more than just the question mark, so append with ampersand
        qs = qs + "&";
    }
    qs = qs + param;
    window.location.search = qs;
    
    0 讨论(0)
  • 2020-11-22 03:22

    Here's my slightly different approach to this, written as an excercise

    function addOrChangeParameters( url, params )
    {
      let splitParams = {};
      let splitPath = (/(.*)[?](.*)/).exec(url);
      if ( splitPath && splitPath[2] )
        splitPath[2].split("&").forEach( k => { let d = k.split("="); splitParams[d[0]] = d[1]; } );
      let newParams = Object.assign( splitParams, params );
      let finalParams = Object.keys(newParams).map( (a) => a+"="+newParams[a] ).join("&");
      return splitPath ? (splitPath[1] + "?" + finalParams) : (url + "?" + finalParams);
    }
    

    usage:

    const url = "http://testing.com/path?empty&value1=test&id=3";
    
    addOrChangeParameters( url, {value1:1, empty:"empty", new:0} )
    
    "http://testing.com/path?empty=empty&value1=1&id=3&new=0"
    
    0 讨论(0)
  • 2020-11-22 03:23

    Here's my approach: The location.params() function (shown below) can be used as a getter or setter. Examples:

    Given the URL is http://example.com/?foo=bar&baz#some-hash,

    1. location.params() will return an object with all the query parameters: {foo: 'bar', baz: true}.
    2. location.params('foo') will return 'bar'.
    3. location.params({foo: undefined, hello: 'world', test: true}) will change the URL to http://example.com/?baz&hello=world&test#some-hash.

    Here is the params() function, which can optionally be assigned to the window.location object.

    location.params = function(params) {
      var obj = {}, i, parts, len, key, value;
    
      if (typeof params === 'string') {
        value = location.search.match(new RegExp('[?&]' + params + '=?([^&]*)[&#$]?'));
        return value ? value[1] : undefined;
      }
    
      var _params = location.search.substr(1).split('&');
    
      for (i = 0, len = _params.length; i < len; i++) {
        parts = _params[i].split('=');
        if (! parts[0]) {continue;}
        obj[parts[0]] = parts[1] || true;
      }
    
      if (typeof params !== 'object') {return obj;}
    
      for (key in params) {
        value = params[key];
        if (typeof value === 'undefined') {
          delete obj[key];
        } else {
          obj[key] = value;
        }
      }
    
      parts = [];
      for (key in obj) {
        parts.push(key + (obj[key] === true ? '' : '=' + obj[key]));
      }
    
      location.search = parts.join('&');
    };
    
    0 讨论(0)
提交回复
热议问题