#&q=car&category=Car%20Audio%2CAccessories&brand=
Run Code Online (Sandbox Code Playgroud)
我从之前提出的SO问题中借用了这个函数:
function insertParam(key, value)
{
key = escape(key); value = escape(value);
var kvp = document.location.hash.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
document.location.hash = kvp.join('&');
}
Run Code Online (Sandbox Code Playgroud)
我这样使用它:
insertParam("category",xy);
insertParam("brand",zy);
Run Code Online (Sandbox Code Playgroud)
我的问题是它将逗号解码为%2C.我知道我可以处理服务器端的字符,但是如何使用javascript使其看起来很漂亮?漂亮我的意思是用逗号替换%2c.
Che*_*ery 13
我不知道为什么在以前的答案中被删除了,但答案是正确的。
alert(decodeURIComponent('%2C'));
Run Code Online (Sandbox Code Playgroud)
因此,您将查询字符串分解为元素,并按 & 符号拆分。比您通过 = 符号拆分结果并对名称和值应用 decodeURIComponent 。
ps:key = escape(key); value = escape(value);你不应该在这里使用转义(不同的浏览器是不同的。“不同”我的意思是IE)。使用 encodeURIComponent。
pps:because they either encode commas or don't encode &=???
alert(encodeURIComponent('&=,'));
Run Code Online (Sandbox Code Playgroud)
产出 %26%3D%2C
decodeURIComponent(foo)就是您正在寻找的东西。
编辑:误读了你的问题。
使用replace(/&/g, "%26").replace(/=/g, "%3D")而不是escapeon key 和 value 来执行此操作。
这 3 个函数都不能完成此任务encodeURI,因为它们要么对逗号进行编码,要么不进行编码。encodeURIComponentencode&=