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.

3 Answers 3

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!

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much. but it throws an error in the line: parameters.splice('destination', 1); saying: "Object#<Object> has no method 'splice' The params are being parsed ok, btw
I've edited my answer, you must use delete method with objects. Splice is only for numeric arrays.
@Sebj It wouldn't join properly that way either. You should join it with = between key and value.
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);

5 Comments

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... :)
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)
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...
It works here. 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.
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...
0

Ok, found something that works!

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

5 Comments

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.
it actually does work... :) X* can be an empty string as well
See here, it doesn't work: 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.
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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.