如何检查查询字符串是否已存在

时间:2016-10-14 11:49:21

标签: javascript jquery query-string

我有两个不同的查询字符串:?pid=?ref=。目前,我使用window.history.pushState添加查询字符串。如何检查是否已存在查询字符串以避免使用?pid=foo?ref=bar而不是?pid=foo&ref=bar

当前代码:

if (!!$.cookie('myrefcookie')) {
  var myref = $.cookie("myrefcookie")
  var target = window.location.href + '?ref=' + myref;
  window.history.pushState(null, null, target);
}

1 个答案:

答案 0 :(得分:1)

您可以检查window.location.search是否有问号。

if (!!$.cookie('myrefcookie')) {
  var myref = $.cookie("myrefcookie");
  var query = window.location.search.indexOf('?') === -1 ? '?ref=' : '&ref=';
  var target = window.location.href + query + myref;
  window.history.pushState(null, null, target);
}
相关问题