5

I am trying to remove some parameters from the url query string.

I have an array of parameters to be removed:

var queryParamsToRemove = ['destination','formName'];

What I was trying to do, is search for each parameter in the url, and remove it using a RegExp. Something like this:

for (param in queryParamsToRemove){
     patt = new RegExp(param,'g');
     queryString = queryString.replace('&' + patt + '=' + /*?=&/g,'');
}

But this doesn't work, because of syntax problems, I guess.

Termininja
  • 6,620
  • 12
  • 48
  • 49
yogev
  • 159
  • 9

3 Answers3

1

Here is a function that I often use in my projects, it allows you to fetch all GET parameters in an associative array:

function urlGet()
{   
    var t = location.search.substring(1).split('&');
    var f = new Object();
    for (var i = 0; i < t.length; i++)
    {
        var x = t[i].split('=');
        f[x[0]] = x[1];
    }
    return f;
}

You can use this function to get all parameters and then, remove from array the parameters you don't want with delete method.

var parameters = urlGet();
delete parameters.destination;
delete parameters.formName;

You now just have to build a new query string.

var query = '?';

for (var prop in parameters) 
{
    query += prop + '=' + parameters[prop] + '&';
};

query = query.substr(0, query.length - 1);

Now, add it to your base url and you're done!

Sebj
  • 476
  • 3
  • 15
  • Thank you very much. but it throws an error in the line: parameters.splice('destination', 1); saying: "Object# has no method 'splice' The params are being parsed ok, btw – yogev Apr 09 '14 at 10:15
  • I've edited my answer, you must use `delete` method with objects. Splice is only for numeric arrays. – Sebj Apr 09 '14 at 12:07
  • @Sebj It wouldn't join properly that way either. You should join it with `=` between key and value. – Colandus Apr 09 '14 at 12:09
0

To answer your real real question:

for (param in queryParamsToRemove){
    queryString = queryString.replace(new RegExp('[&\?]' + queryParamsToRemove[param] + '=.*(&?)', 'g'), '\1');
}

That should work.

Otherwise you could use a function like this one: The $.param( ) inverse function in JavaScript / jQuery (Simply remove jQuery from function name and you can use it without any library).

Something like this:

unparam = function (value) {
    var
    // Object that holds names => values.
    params = [],
    // Get query string pieces (separated by &)
    pieces = value.split('&'),
    // Temporary variables used in loop.
    pair, i, l;

    // Loop through query string pieces and assign params.
    for (i = 0, l = pieces.length; i < l; i++) {
        pair = pieces[i].split('=', 2);
        // Repeated parameters with the same name are overwritten. Parameters
        // with no value get set to boolean true.
        params[decodeURIComponent(pair[0])] = (pair.length == 2 ?
            decodeURIComponent(pair[1].replace(/\+/g, ' ')) : true);
    }

    return params;
};

var query = unparam(querystr);
for(var i in queryParamsToRemove) {
    delete query[queryParamsToRemove[i]];
}

Turning the query string into an array, and from there you can remove your values and convert it back to a query string. If you use jQuery you can use jQuery.param()

Otherwise it shouldn't be too hard to make your own function.

To now convert the query array into a string we could do:

reparam = function (queryArray) {
    var res = [];

    for(var i in queryArray) {
        res.push(i + "=" + queryArray[i]);   
    }

    return res.join('&');
}

var queryString = reparam(query);
Community
  • 1
  • 1
Colandus
  • 1,634
  • 13
  • 21
  • Thank you very much for that answer. One thing - the first short part removes the keys just fine, but keeps the values in place. If it is possible to modify it so it removes the values as well and avoid the long coding for that rather simple task... :) – yogev Apr 09 '14 at 10:26
  • If you speak of the regex, then as I said it wasn't the best and only considers letters for the value... You'd need to modify the regex to make it recognize the values properly (which may be a rather complex task, unless you find a ready regex for it on the net) – Colandus Apr 09 '14 at 10:28
  • my query string is: formGeneratorNative.php?1=1&width=1920&height=979&device=tablet&isEmulator=false&deviceCategory=3&destination=lobbyWrapper.php&formName=Login So the values are indeed words. I don't understand why the are not being removed... – yogev Apr 09 '14 at 10:35
  • It works here. http://jsfiddle.net/d9K7L/ (check console), also the "formGeneratorNative.php?" part shouldn't be part of the query string! It may not be relevant in this case though, but the other methods with splitting it into an array would not work smoothly with it. – Colandus Apr 09 '14 at 10:46
  • Thank you again. but if you look closely, it does'nt work. The output is: formGeneratorNative.php?1=1&width=1920&height=979&device=tablet&isEmulator=false‌​&deviceCategory=3lobbyWrapper.phpLogin and ass you can see, "lobbyWrapper.phpLogin" is still there... – yogev Apr 09 '14 at 11:15
0

Ok, found something that works!

for (param in queryParamsToRemove) {
    queryString = queryString.replace(new RegExp('&(' + queryParamsToRemove[param] + '=)+((\w)*(.)*)*&', 'g'), '&');
}
Termininja
  • 6,620
  • 12
  • 48
  • 49
yogev
  • 159
  • 9
  • That will not work when the params to remove are at end of the query string (or beginning). As in your example, formName will not be removed. I will update my answer, check it. – Colandus Apr 09 '14 at 11:28
  • it actually does work... :) X* can be an empty string as well – yogev Apr 09 '14 at 12:03
  • See here, it doesn't work: http://jsfiddle.net/d9K7L/2/ formName will not be removed as it is the last one. Also if it was the first one, same there (which is why you shouldn't use the filename in the query string). Also all that comes after "destination" is removed as well. – Colandus Apr 09 '14 at 12:05
  • That is odd... I took out the file name off of the query string, and it works just fine for me. I can see it's not working in the fiddle. Can't see why. I'll give it another look – yogev Apr 09 '14 at 12:35
  • Ho, I can see why it's not suppose to work.because i don't have the '&' after the 'Login'... So i think i will just add &1=1 at the end of the url as well. – yogev Apr 09 '14 at 12:43