在 Javascript 中获取查询字符串数组值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15865747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get querystring array values in Javascript
提问by iltdev
I have a form that uses the get method and contains an array:
我有一个使用 get 方法并包含一个数组的表单:
http://www.example.com?name[]=hello&name[]=world
http://www.example.com?name[]=hello&name[]=world
I'm trying to retrieve array values 'hello' and 'world' using JavaScript or jQuery.
我正在尝试使用 JavaScript 或 jQuery 检索数组值“hello”和“world”。
I've had a look at similar solutions on Stack Overflow (e.g. How can I get query string values in JavaScript?) but they seem to only deal with parameters rather than arrays.
我在 Stack Overflow 上看过类似的解决方案(例如,如何在 JavaScript 中获取查询字符串值?)但它们似乎只处理参数而不是数组。
Is it possible to get array values?
是否可以获取数组值?
回答by Adidi
There you go: http://jsfiddle.net/mm6Bt/1/
你去吧:http: //jsfiddle.net/mm6Bt/1/
function getURLParam(key,target){
var values = [];
if (!target) target = location.href;
key = key.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var pattern = key + '=([^&#]+)';
var o_reg = new RegExp(pattern,'ig');
while (true){
var matches = o_reg.exec(target);
if (matches && matches[1]){
values.push(matches[1]);
} else {
break;
}
}
if (!values.length){
return null;
} else {
return values.length == 1 ? values[0] : values;
}
}
var str = 'http://www.example.com?name[]=hello&name[]=world&var1=stam';
console.log(getURLParam('name[]',str));
console.log(getURLParam('var1',str));