Javascript URL 查询字符串逻辑

Javascript URL Query String Logic

我有一个事件列表页面,可以使用查询字符串变量按类型和日期进行过滤。

我正在尝试使用 javascript/jQuery 实现以下逻辑。

我有一个日历,它在更新时触发一个功能。解雇后我需要实现以下逻辑:

我尝试了各种方法来实现这一点,但我一直遇到将信息附加到 URL 末尾而不是替换其中部分的问题。

如有任何帮助,我们将不胜感激。

谢谢。

您可以尝试这样的操作:

注意:未测试。

var newDateValue;
var myPath = window.location.pathname

//check if path contains the different variables
var containsFilter = myPath.indexOf("?filter=") != -1 ? true : false;
var containsAppendedDateStart = myPath.indexOf("&dateStart=" != -1 ? true : false;
var containsDateStart = myPath.indexOf("?dateStart=" != -1 ? true : false;

if(containsFilter && !containsAppendedDateStart){

   // If the current URL contains ?filter= then add &dateStart= to the end of the URL.
   window.location.replace(window.location.href + "&dateStart=");
}else if(containsFilter && containsAppendedDateStart){

   //If the current URL contains ?filter= AND &dateStart= then keep the current filter value but replace the date query string with a new one.
   newDateValue = 10; // add your new value here
   var splittedPathArray = myPath.split("&dateStart=");
   var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "&dateStart=" + addNewValue;
   window.location.replace(newUrl);

}else if(containsDateStart){
   // If the current URL contains ONLY ?dateStart= then replace it with the new one.
   newDateValue = 15;// add your new value here
   var splittedPathArray =  myPath.split("?dateStart=");
   var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "?dateStart=" + addNewValue;
}

使用原生 Web APIvanilla javascript 比使用 jQuery。至于 jQuery 不提供任何特定函数来处理查询字符串。

新的 URLSearchParams 对象提供了一些方法可以更轻松地处理 URL 查询字符串。例如,在您的情况下,您需要执行以下操作:

function updateQueryString(queryString, dateStart) {
  var queryString = new URLSearchParams(queryString);
  queryString.has('dateStart')
    ? queryString.set('dateStart', dateStart)
    : queryString.append('dateStart', dateStart);
  return queryString.toString();
}

对于此解决方案,您需要一个 polyfill

遗憾的是,大多数网络浏览器尚未实现此功能,您需要 "polyfill" URLSearchParams 对象以使此解决方案正常工作。您必须将此行添加到 html:

中的 <head> 部分
<script src="https://cdn.rawgit.com/inexorabletash/polyfill/v0.1.14/polyfill.min.js"></script>

您可以找到有关 URLSearchParams in the Mozilla Developers Network Documentation, the WHATWG specification for the URL Standard or the specification by the W3C

的更多信息

没有 polyfill 的解决方案

如果你不喜欢使用 edge 功能,你仍然可以在没有任何额外的 polyfill 的情况下使用它。它看起来像这样:

function updateQueryString(queryString, dateStart) {
  var qsObject = {};
  queryString
    .substring(1) // ignore '?'
    .split('&').forEach(function (param) {
      param = param.split('=');
      qsObject[param[0]] = param[1];
    });
  qsObject['dateStart'] = dateStart;
  return '&' + Object.keys(qsObject)
    .map(function (key) {
      return key + '=' + qsObject[key];
    })
    .join('?');
}

调用任何版本的 updateQueryString 函数,你喜欢这样:

updateQueryString(windonw.location.search, dateStart)