MAHAR MAHAR - 4 months ago 15
Javascript Question

Remove match word using jQuery

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

Answer

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)