Reputation: 800
I have an Ajax select input that changes the URL when changed, the page does not refresh. However when the select input is changed multiple times, repeated parameters stack in the URL:
[domain]/find.php?cat=1#pricemin=10&pricemax=500#pricemin=10&pricemax=500
How can I use javascript to encode it back to:
[domain]/find.php?cat=1#pricemin=10&pricemax=500
so that there are no duplicate parameters?
An example of my current jQuery is as below:
$('#filterform select').on('change', function(e){
var dummy = $('#filterform').serialize(),
loc = $('<a>', {href:window.location})[0];
someajaxfunction();//do ajax function here
if(history.pushState){
history.pushState(null, null, loc +'#'+ dummy);
}
});
I have tried replacing loc
with loc.pathname
and the repeated parameters problem is solved. However my ?cat=1
form parameter is gone as well which is not desired. I wish to look at this problem with a URL search-and-modify jQuery/javascript method, for example:
What we have is
[domain]/find.php?cat=1&subcats%5B%5D=1&subcats%5B%5D=2
What we want is
[domain]/find.php?cat=1&subcats=1+2
Is it possible?
Note: 5 minutes after posting this question I realised that using loc.pathname + loc.search
solves my problem, sorry for the long post. I am still curious about a URL search-and-modify jQuery/javascript method. Would appreciate if anyone can provide a starting point, thanks!
Upvotes: 0
Views: 4070
Reputation: 819
function removeDuplicate(url) {
url = decodeURIComponent(url); // decode the url, %5B becomes [ and ,%5D becomes ]. Hence the url becomes [domain]/find.php?cat=1&subcats[]=1&subcats[]=2
var query = url.split('?')[1]; // get only the query
var parts = query.split('&'); // split the query into parts: cat=1, subcats[]=1, subcats[]=2
var params = {};
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
var value = nv[1] || true;
if (params[nv[0]] && params[nv[0]].indexOf(value)) {
params[nv[0]].push(value);
} else {
params[nv[0]] = [value];
}
}
url = url.split('?')[0] + '?';
var keys = Object.keys(params);
for (var i = 0; i < keys.length; i++) {
url += keys[i] + '=' + params[keys[i]].join('+');
if (i !== keys.length - 1) url += '&';
}
return url;
}
Upvotes: 2