[英]Get two URL parameters - but need to preserve & symbol
I need to get two parameters from a URL, and they could potensially contain an & symbol or a space. 我需要从URL获取两个参数,并且它们可能潜在地包含&符号或空格。 as part of the search string.
作为搜索字符串的一部分。
Example: mysite.com?param1=Bower & Wilkins?param2=Speakers
示例:
mysite.com?param1=Bower & Wilkins?param2=Speakers
I realize that Bower & Wilkins contains the obvious symbol for getting the second parameter, but can I replace it with something else? 我意识到Bower&Wilkins包含用于获取第二个参数的明显符号,但是我可以用其他东西代替它吗?
When trying this function, can easily return a single parameter: 尝试此功能时,可以轻松返回单个参数:
URL: mysite.com?param1=Bower%20&%20Wilkins
function getQueryStringValue(key) {
return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^]*))?)?.*$", "i"), "$1"));
}
var param1 = getQueryStringValue("param1"); // Bower & Wilkins
How can I get the second parameter and how must I construct the URL. 如何获取第二个参数以及如何构造URL。 Can I use another symbol than & for listing the second parameter?
我可以使用&以外的其他符号列出第二个参数吗?
What I need: 我需要的:
var param1 = getQueryStringValue("param1"); // Bower & Wilkins
var param2 = getQueryStringValue("param2"); // Speakers
The &
within the param needs to be encoded as %26
. 参数中的
&
需要编码为%26
。 This means you need to substitute before running the parameters through encodeURI or use encodeURIComponent on the value. 这意味着您需要先进行替换,然后才能通过encodeURI运行参数,或者在值上使用encodeURIComponent。
The input should be "mysite.com?param1=Bower%20%26%20Wilkins¶m2=Speakers"
. 输入应为
"mysite.com?param1=Bower%20%26%20Wilkins¶m2=Speakers"
。
To get the result you could try something like this 为了得到结果,您可以尝试这样的事情
function getQueryStringValue(url, key) {
var params = {};
var url_params = url.split("?", 2);
if (url_params.length > 1) {
var param_list = url_params[1].split("&");
param_list.map(function (param_str) {
var kv = param_str.split("=", 2);
params[kv[0]] = kv[1];
});
}
return (key in params)? decodeURIComponent(params[key]) : ''
}
var url = "mysite.com?param1=Bower%20%26%20Wilkins¶m2=Speakers";
console.log("Bower & Wilkins" === getQueryStringValue(url, "param1"));
console.log("Speakers" === getQueryStringValue(url, "param2"));
console.log("" === getQueryStringValue(url, "param3"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.