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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With