Reputation: 5
I want to split and join two type of url. For example
Url 1 :
http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC
Url 2 :
http://localhost/site/index.php?route=product/category&path=20&limit=8
<input type="hidden" class="sort" value="http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC" />
<input type="hidden" class="limit" value="http://localhost/site/index.php?route=product/category&path=20&limit=8" />
I'd like to join the query strings but remove duplicates.
I'm looking for this result at last
http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC&limit=8
Upvotes: 0
Views: 64
Reputation: 18995
You could go with getting the query parameters in an array and de-duplicating them.
var url1 = "http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC";
var url2 = "http://localhost/site/index.php?route=product/category&path=20&limit=8";
var url = (url1.split`?`[1]+"&"+url2.split`?`[1]);
var result = url1.split`?`[0]+"?"+Array.from(new Set(url.split`&`)).join`&`;
console.log(result)
Note that you're left with order=ASC
and order=DESC
, of which only the last is processed. But looks like that's what you want...
For older browsers:
var url1 = "http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC";
var url2 = "http://localhost/site/index.php?route=product/category&path=20&limit=8";
var url = (url1.split('?')[1]+"&"+url2.split('?')[1]);
var result = url1.split('?')[0]+"?"+url.split('&').filter(function(x,i){
return url.split('&').indexOf(x) == i;
}).join('&');
console.log(result)
Upvotes: 0
Reputation: 10675
var getUrlParameter = function getUrlParameter(sParam, url) {
var sPageURL = decodeURIComponent(url),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
Now read individual parametrs by
var order = getUrlParameter('order', 'http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC');
var limit = getUrlParameter('limit', 'http://localhost/site/index.php?route=product/category&path=20&limit=8');
and make a new url by using the parameters.
Upvotes: 1