xd3*_*d3v 10 javascript jquery query-string
我一直在为此而奋斗.
使用jquery或javascript,我如何切换变量和值,然后重建查询字符串?例如,我的起始网址是:
http://example.com?color=red&size=small,medium,large&shape=round
Run Code Online (Sandbox Code Playgroud)
然后,如果用户点击标有"红色"的按钮,我想最终得到:
http://example.com?size=small,medium,large&shape=round //color is removed
Run Code Online (Sandbox Code Playgroud)
然后,如果用户再次点击"红色",我想最终得到:
http://example.com?size=small,medium,large&shape=round&color=red //color is added back
Run Code Online (Sandbox Code Playgroud)
然后,如果用户单击标有"中"的按钮,我想最终得到:
http://example.com?size=small,large&shape=round&color=red //medium is removed from list
Run Code Online (Sandbox Code Playgroud)
然后,如果用户再次点击标记的"媒介",我想最终得到:
http://example.com?size=small,large,medium&shape=round&color=red //medium added back
Run Code Online (Sandbox Code Playgroud)
变量的顺序并不重要; 我刚刚把它们搞定到最后.
function toggle(url, key, val) {
var out = [],
upd = '',
rm = "([&?])" + key + "=([^&]*?,)?" + val + "(,.*?)?(&.*?)?$",
ad = key + "=",
rmrplr = function(url, p1, p2, p3, p4) {
if (p2) {
if (p3) out.push(p1, key, '=', p2, p3.substr(1));
else out.push(p1, key, '=', p2.substr(0, p2.length - 1));
} else {
if (p3) out.push(p1, key, '=', p3.substr(1));
else out.push(p1);
}
if (p4) out.push(p4);
return out.join('').replace(/([&?])&/, '$1').replace(/[&?]$/, ''); //<!2
},
adrplr = function(s) {
return s + val + ',';
};
if ((upd = url.replace(new RegExp(rm), rmrplr)) != url) return upd;
if ((upd = url.replace(new RegExp(ad), adrplr)) != url) return upd;
return url + (/\?.+/.test(url) ? '&' : '?') + key + '=' + val; //<!1
}
Run Code Online (Sandbox Code Playgroud)
params自我描述不够,希望对此有所帮助.
!1:从改变...? '&' : ''到... ? '&' : '?'
!2:从改变.replace('?&','?')...到.replace(/([&?]&)/,'$1')...
http://jsfiddle.net/ycw7788/Abxj8/
我编写了一个函数,它可以有效地产生预期的行为,而不使用任何库或框架.一个动态演示,可以发现这个小提琴:http://jsfiddle.net/w8D2G/1/
定义:
所显示的示例值将在Usage部分被使用,以下
-草堆-要搜索的字符串中(默认=查询字符串例如:?size=small,medium)
-针-搜索的关键.示例:size
- 值 - 要替换/添加的值.示例:medium.
用法(例如:)input > output:
qs_replace(needle, value)?size=small,medium > ?size=small?size=small > size=small,mediumqs_replace(needle, options) 对象选项.认可的选择:
findtrue如果值存在false则返回,否则返回.add,remove或字符串.添加/删除给定值.如果使用,并且值是唯一的值,也会被删除.如果值已存在,则不会添加该值.toggleneedleremoveneedleignorecaseneedle,add,remove或find).separatorneedle.默认为逗号(,).注意:haystack通过将String 添加为第一个参数,也可以定义String的不同值:qs_replace(haystack, needle, value)或qs_replace(haystack, needle, options)
代码(底部的例子).小提琴:http://jsfiddle.net/w8D2G/1/:
function qs_replace(haystack, needle, options) {
if(!haystack || !needle) return ""; // Without a haystack or needle.. Bye
else if(typeof needle == "object") {
options = needle;
needle = haystack;
haystack = location.search;
} else if(typeof options == "undefined") {
options = needle;
needle = haystack;
haystack = location.search;
}
if(typeof options == "string" && options != "") {
options = {remove: options};
var toggle = true;
} else if(typeof options != "object" || options === null) {
return haystack;
} else {
var toggle = !!options.toggle;
if (toggle) {
options.remove = options.toggle;
options.toggle = void 0;
}
}
var find = options.find,
add = options.add,
remove = options.remove || options.del, //declare remove
sep = options.sep || options.separator || ",", //Commas, by default
flags = (options.ignorecase ? "i" :"");
needle = encodeURIComponent(needle); //URL-encoding
var pattern = regexp_special_chars(needle);
pattern = "([?&])(" + pattern + ")(=|&|$)([^&]*)(&|$)";
pattern = new RegExp(pattern, flags);
var subquery_match = haystack.match(pattern);
var before = /\?/.test(haystack) ? "&" : "?"; //Use ? if not existent, otherwise &
var re_sep = regexp_special_chars(sep);
if (!add || find) { //add is not defined, or find is used
var original_remove = remove;
if (subquery_match) {
remove = encodeURIComponent(remove);
remove = regexp_special_chars(remove);
remove = "(^|" + re_sep + ")(" + remove + ")(" + re_sep + "|$)";
remove = new RegExp(remove, flags);
var fail = subquery_match[4].match(remove);
} else {
var fail = false;
}
if (!add && !fail && toggle) add = original_remove;
}
if(find) return !!subquery_match || fail;
if (add) { //add is a string, defined previously
add = encodeURIComponent(add);
if(subquery_match) {
var re_add = regexp_special_chars(add);
re_add = "(^|" + re_sep + ")(" + re_add + ")(?=" + re_sep + "|$)";
re_add = new RegExp(re_add, flags);
if (subquery_match && re_add.test(subquery_match[4])) {
return haystack;
}
if (subquery_match[3] != "=") {
subquery_match = "$1$2=" + add + "$4$5";
} else {
subquery_match = "$1$2=$4" + sep + add + "$5";
}
return haystack.replace(pattern, subquery_match);
} else {
return haystack + before + needle + "=" + add;
}
} else if(subquery_match){ // Remove part. We can only remove if a needle exist
if(subquery_match[3] != "="){
return haystack;
} else {
return haystack.replace(pattern, function(match, prefix, key, separator, value, trailing_sep){
// The whole match, example: &foo=bar,doo
// will be replaced by the return value of this function
var newValue = value.replace(remove, function(m, pre, bye, post){
return pre == sep && post == sep ? sep : pre == "?" ? "?" : "";
});
if(newValue) { //If the value has any content
return prefix + key + separator + newValue + trailing_sep;
} else {
return prefix == "?" ? "?" : trailing_sep; //No value, also remove needle
}
}); //End of haystack.replace
} //End of else if
} else {
return haystack;
}
// Convert string to RegExp-safe string
function regexp_special_chars(s){
return s.replace(/([[^$.|?*+(){}\\])/g, '\\$1');
}
}
Run Code Online (Sandbox Code Playgroud)
示例(小提琴:http://jsfiddle.net/w8D2G/1/):
qs_replace('color', 'red'); //Toggle color=red
qs_replace('size', {add: 'medium'}); //Add `medium` if not exist to size
var starting_url = 'http://example.com?color=red&size=small,medium,large&shape=round'
starting_url = qs_replace(starting_url, 'color', 'red'); //Toggle red, thus remove
starting_url = qs_replace(starting_url, 'color', 'red'); //Toggle red, so add it
alert(starting_url);
Run Code Online (Sandbox Code Playgroud)