使用jQuery删除匹配单词

时间:2016-07-30 13:34:38

标签: javascript jquery

我想拆分并加入两种类型的网址。例如
网址1:
http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC
网址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" />

我想加入查询字符串但删除重复项。

我正在寻找这个结果

http://localhost/site/index.php?route=product/category&path=20&sort=p.price&order=ASC&order=DESC&limit=8

2 个答案:

答案 0 :(得分:1)

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];
        }
    }
};

现在通过

读取各个参数
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');

并使用参数创建一个新网址。

答案 1 :(得分:0)

您可以在数组中获取查询参数并de-duplicating

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)

请注意,您只剩下order=ASCorder=DESC,其中只有最后一个被处理。但看起来这就是你想要的......

对于旧版浏览器:

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)