使用JS根据其值删除部分查询字符串,而不重新加载页面

时间:2017-10-14 09:30:24

标签: javascript jquery

如何根据参数从URL中删除某些参数? 例如,如果我想以编程方式删除任何包含值" all"的参数集。即Ajax事件完成时。

www.foobar.com/page?year=all&language=all&gender=female 至: www.foobar.com/page?gender=female

使用JS或jQuery。

3 个答案:

答案 0 :(得分:0)

var queryParameters = {}, queryString = location.search.substring(1),
    re = /([^&=]+)=([^&]*)/g, m;

while (m = re.exec(queryString)) {
    queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}

// Add new parameters or update existing ones
queryParameters['newParameter'] = 'new parameter';
queryParameters['existingParameter'] = 'new value';
location.search = $.param(queryParameters);

答案 1 :(得分:0)



// Handy function to parse the URL and get a map of the query parameters
function parseQueryParameters(url) {
  var qp = {};
  if (!url) {
    return qp;
  }
  var queryString = url.split('?')[1];
  if (!queryString) {
    return qp;
  }

  return queryString.split('&')
    .reduce(function(m, d) {
      var splits = d.split('=');
      var key = splits[0];
      var value = splits[1];
      if (key && value) {
        m[key] = value;
      }
      return m;
    }, qp);

}

//Function to build a url given a map of query parameters
function buildUrl(url, queryParams) {
  if (!url) {
    return null;
  }
  if (!queryParams) {
    return url;
  }
  return Object.keys(queryParams)
    .reduce(function(m, key, i) {
      m += ((i === 0 ? "?" : "&") + key + "=" + queryParams[key]);
      return m;
    }, url)
}

function cleanUrl(url) {
  //If no URL was provided, do nothing
  if (!url) return;

  //Parse and get all query parameters as a map
  var qp = parseQueryParameters(url);

  //Create a new map to hold the filtered query parameters
  var newQp = {};

  //For each query paremeter check the value and add only the required ones to the new map
  //PS: You can also use map/reduce/filter to do this
  //Using a simple for loop here for clarity
  var keys = Object.keys(qp);
  for (var i = 0; i < keys.length; i++) {
    var currentKey = keys[i];
    //Add only if parameter value is not 'all'
    if (qp[currentKey] !== 'all') {
      newQp[currentKey] = qp[currentKey];
    }
  }
  
  //Build new URL from filtered query parameters
  return buildUrl(url.split('?')[0], newQp);
}

//Call cleanUrl with URL 
cleanUrl("http://example.com?a=all&b=all&c=none"); //Returns "http://example.com?c=none"
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用URL()构造函数URLSearchParams()来获取URL的查询字符串,作为与查询字符串参数Array和{对应的属性和值数组的Array.prototype.filter() {1}}从数组中删除查询字符串参数,再次RegExp.prototype.test()重新构建已过滤的查询字符串参数

URLSearchParams()