Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove parameters from url query?

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.

like image 295
yogev Avatar asked Nov 10 '22 09:11

yogev


1 Answers

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!

like image 158
Sebj Avatar answered Nov 14 '22 21:11

Sebj