Change URL parameters

前端 未结 26 2632
孤独总比滥情好
孤独总比滥情好 2020-11-22 08:40

I have this URL:

site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc

what I need is to be able to

26条回答
  •  我在风中等你
    2020-11-22 08:59

    Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the URL:

    window.history.replaceState('object or string', 'Title', 'page.html' + editParams('sorting', ModifiedTimeAsc));
    
    
    // background functions below:
    
    // add/change/remove URL parameter
    // use a value of false to remove parameter
    // returns a url-style string
    function editParams (key, value) {
      key = encodeURI(key);
    
      var params = getSearchParameters();
    
      if (Object.keys(params).length === 0) {
        if (value !== false)
          return '?' + key + '=' + encodeURI(value);
        else
          return '';
      }
    
      if (value !== false)
        params[key] = encodeURI(value);
      else
        delete params[key];
    
      if (Object.keys(params).length === 0)
        return '';
    
      return '?' + $.map(params, function (value, key) {
        return key + '=' + value;
      }).join('&');
    }
    
    // Get object/associative array of URL parameters
    function getSearchParameters () {
      var prmstr = window.location.search.substr(1);
      return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
    }
    
    // convert parameters from url-style string to associative array
    function transformToAssocArray (prmstr) {
      var params = {},
          prmarr = prmstr.split("&");
    
      for (var i = 0; i < prmarr.length; i++) {
        var tmparr = prmarr[i].split("=");
        params[tmparr[0]] = tmparr[1];
      }
      return params;
    }
    

提交回复
热议问题