gpt4 book ai didi

javascript - 处理JS中的查询字符串,如http_build_query等

转载 作者:行者123 更新时间:2023-12-02 19:06:56 25 4
gpt4 key购买 nike

这就是我所拥有的

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:

  • 域名.com
  • domain.com/path/to/sth/
  • domain.com/?site_type=normal
  • 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);

最佳答案

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

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

然后适本地设置 queryString 上的 site_type

queryString["site_type"] = "normal";

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

var searchString = "";
for ( q in queryString ) {
searchString+="&" + q + "=" + queryString[q];
}
window.location.search = searchString;

关于javascript - 处理JS中的查询字符串,如http_build_query等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14226811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com