0

这就是我所拥有的

if(condition1) {
     location.href = location.href+'/?site_type=normal';
}
else if(condition2) {
    location.href = location.href+'/?site_type=other';
}

当然,如果 location.href 上已经有查询变量,那就有问题了,等等。

我需要

  1. 从查询字符串中查找变量
  2. 如果 site_type 已经存在,则将该值替换为“正常”或“其他”
  3. 使用新的 site_type 重建 url

编辑:我发现我需要考虑各种 URL:

  • 域名.com
  • domain.com/path/to/sth/
  • domain.com/?site_type=正常
  • domain.com?var=123&foo=987
  • domain.com/path/?site_type=normal&var=123&foo=987

所以,这是我想出的,欢迎提出建议:

var searchstring = window.location.search;
var url = window.location.href;

console.log('search: ' +  searchstring);
console.log( 'url: ' +  url);
// strip search from url
url = url.replace(searchstring,"");
console.log( 'url: ' +  url);
//strip site_type from search
searchstring = searchstring.replace("&site_type=normal","")
                        .replace("&site_type=other","")
                        .replace("?site_type=normal","")
                        .replace("?site_type=other","")
                        .replace("?","")
                        ;
console.log('search: ' +  searchstring);
if(searchstring != ''){searchstring = '&' + searchstring;}
var final = url + '?site_type=normal' + searchstring;
final = final.replace("&&","&");
console.log('final: ' +  final);
4

3 回答 3

2

您可以使用 直接访问查询字符串window.location.search。您可以使用此处找到的正则表达式技巧将其转换为对象。

var queryString = {};
window.location.search.replace(/([^?=&]+)(=([^&]*))?/g, function($0, $1, $2, $3) {
  queryString[$1] = $3; }
);

然后适当地设置site_typequeryString

queryString["site_type"] = "normal";

最后,将其转换回字符串并将其设置为window.location.search.

var searchString = "";
for ( q in queryString ) {
  searchString+="&" + q + "=" + queryString[q];
}
window.location.search = searchString;
于 2013-01-09T01:26:50.930 回答
0

这是一种方法:

//remove existing param and append new one..
var newHref = window.location.href.replace(window.location.search,"") + '?site_type=other';

//change href
window.location.href = newHref;

仅当您有一个要替换的参数时才有效,否则它将删除所有参数。

于 2013-01-09T01:24:28.000 回答
0

例如,如果你有

yourpage.com/?site_type=normal

你只需要网站而不是查询你可以清除它们的变量

var novars= location.href.replace(window.location.search,"")

这种情况下 novars = youroage.com

为了获取变量,您可以这样做:

var site_type = window.location.search.replace("?site_type=","");

在这里,我将获得 site_type 值,无论它是正常的还是其他的

这种情况下你的变量site_type = "normal"

对于重建 url,你可以添加新的 site_type

location.href = novars+"?site_type=normal"

或者

location.href = novars+"?site_type=other"
于 2013-01-09T01:31:53.763 回答