Rotan075 Rotan075 - 3 years ago 255
jQuery Question

Getting URL parameters and filter out a specific parameter

I want to filter out a specific parameter out of the URL. I have the following situation:

  1. The page got loaded (for example:

  2. When the page is loaded a function is called to push a entry to the history (pushState): ( for example:

  3. Now I want to call a function that reads all the parameters and output all these parameters expect for the state. So that I end up with: "?folder=app&test=true" (just a string value, no array or object). Please keep in mind that I do not know what all the names of the parameters are execpt for the

What I have tried

I know I can get all the parameters by using the following code:

But it will result in:


I try to split the url, for example:

var url = '?folder=app&test=true&state=1';
url = url.split('&state=');

But that does not work. Also because the
number is dynamic in each request. A solution might be remove the last parameter out of the url but I also do not know if that ever will be the case therefore I need some filtering mechanisme that will only filter out the

state=/*regex for a number*/

Answer Source

To achieve this you can convert the querystring provided to the page to an object, remove the state property of the result - assuming it exists - then you can convert the object back to a querystring ready to use in pushState(). Something like this:

var qsToObj = function(qs) {
  qs = qs.substring(1);
  if (!qs) return {};    
  return qs.split("&").reduce(function(prev, curr, i, arr) {
    var p = curr.split("=");
    prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
    return prev;
  }, {});

var qs = '?'; //;
var obj = qsToObj(qs);
delete obj.state;

var newQs = $.param(obj);
<script src=""></script>

Credit to this answer for the querystring to object logic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download