How can I add or update a query string parameter?

后端 未结 27 2886
别那么骄傲
别那么骄傲 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: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('&');
    };
    

提交回复
热议问题