1

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*/
Rotan075
  • 2,567
  • 5
  • 32
  • 54

5 Answers5

7

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • But this will not work if the url does not contain any parameters right? It will return "=undefined" and if only the "state" is added to url then it will only return "state=1" Is it also possible to build this inside the function? – Rotan075 Oct 03 '17 at 10:03
  • 1
    In that case you just need to check for an empty querystring. I updated the answer for you – Rory McCrossan Oct 03 '17 at 10:12
3

A much simpler way to do this would be:

  let url = new URL(window.location.href)

  url.searchParams.delete('state');
  window.location.search = url.search;

You can read about URLSearchParams.delete() in the MDN Web Docs.

therealrodk
  • 386
  • 2
  • 10
2

I would agree with Rory's answer, you should have an object to safely manipulate params. This is the function that I use.

function urlParamsObj(source) {
    /* function returns an object with url parameters
    URL sample: www.test.com?var1=value1&var2=value2
    USE:    var params = URLparamsObj();
    alert(params.var2)  --> output: value2
    You can use it for a url-like string also: urlParamsObj("www.ok.uk?a=2&b=3")*/
    var urlStr = source ? source : window.location.search ? window.location.search : ""
        if (urlStr.indexOf("?") > -1) { // if there are params in URL
            var param_array = urlStr.substring(urlStr.indexOf("?") + 1).split('&'),
            theLength = param_array.length,
            params = {},
            i = 0,
            x;
            for (; i < theLength; i++) {
                x = param_array[i].toString().split('=');
                params[x[0]] = x[1];
            }
            return params;
        }
        return {};
}
JohnPan
  • 1,185
  • 11
  • 21
-1

Sorry if this is wrong just as i think &state=1,2,3,4,5,6 is absolute its just depends on number to pick states just like my web

var url = '?folder=app&test=true&state=1';
url = url.substring(0, url.indexOf('&s'));
$('#demo').text(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='demo'></span>
-1

var url = '?folder=app&test=true&state=1';
url = url.split('&folder=');
console.log(url);
  • Hi, this question already has several answers and this does not even work, just check the output if you run this snippet. – Jan Nov 18 '20 at 11:55