Rotan075 Rotan075 - 1 year ago 107
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: http://test.com/default.aspx?folder=app&test=true)

  2. When the page is loaded a function is called to push a entry to the history (pushState): ( for example: http://test.com/default.aspx?folder=app&test=true&state=1)

  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
    state
    parameter



What I have tried

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

window.location.search


But it will result in:

?folder=app&test=true&state=1


I try to split the url, for example:



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





But that does not work. Also because the
state
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 = '?'; // window.location.search;
var obj = qsToObj(qs);
delete obj.state;
console.log(obj);

var newQs = $.param(obj);
console.log(newQs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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