用javascript中的数组解析url

用javascript中的数组解析url,javascript,html,regex,parsing,Javascript,Html,Regex,Parsing,我从GET方法中输入url,格式如下 rec_test.html?emotion=Happy&myInputs_1%5B%5D=things&myInputs_1%5B%5D=are&myInputs_1%5B%5D=working&myInputs_2%5B%5D=i&myInputs_2%5B%5D=hope&myInputs_3%5B%5D=so 我正试图用以下代码解析它: function getParameterByName(name)

我从GET方法中输入url,格式如下

rec_test.html?emotion=Happy&myInputs_1%5B%5D=things&myInputs_1%5B%5D=are&myInputs_1%5B%5D=working&myInputs_2%5B%5D=i&myInputs_2%5B%5D=hope&myInputs_3%5B%5D=so
我正试图用以下代码解析它:

function getParameterByName(name){
                    var url = window.location.search;
                    name = name.replace(/[\[\]]/g, "\\$&");
                    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
                    results = regex.exec(url);
                    if (!results) return null;
                    if (!results[2]) return '';
                    return decodeURIComponent(results[2].replace(/\+/g, " "));
                }
但是当我将
myInputs\u 1
传递给函数时,它返回null

我计划以以下格式生成输出:

myInput_1 = ['things', 'are', 'working']
myInput_2 = ['i', 'hope']
myInput_3 = ['so']
但我无法提取单个值。有没有办法达到预期的输出

编辑1

我了解到
%5B
[
%5D
]
,但即使我将
myInput\u 1[]
作为参数传递给函数,它仍然返回null,我不知道为什么可以使用实例的对象:

s = "http://example.com/rec_test.html?emotion=Happy&myInputs_1%5B%5D=things&myInputs_1%5B%5D=are&myInputs_1%5B%5D=working&myInputs_2%5B%5D=i&myInputs_2%5B%5D=hope&myInputs_3%5B%5D=so"

url = new URL(s)
searchParams = url.searchParams

console.log(searchParams.getAll("myInputs_1[]"))
// ["things", "are", "working"]
非正则表达式方式

function getParamByName(name){
    var value = []
    paramsArray = decodeURIComponent(window.location.search).split("?")[1].split("&")
    paramsArray.forEach(function(d){
        if(d.indexOf(name) > -1){
            value.push(d.split("=")[1])
        }
    })
    return value;
}

使用
.exec
执行时,需要执行while循环。另外,我简化了你的正则表达式

function getParameterByName(name){
    var url = decodeURIComponent(window.location.search);
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "=([^&#]*)", 'g');
    var match, result = [];
    while ((match = regex.exec(url)) !== null)
        result.push(match[1]);
    return result;
}

我建议你使用Jean的答案,除非浏览器兼容性对你很重要。

你的答案非常简洁,但我有一个浏览器兼容性要求。将来,如果可能的话,人们应该使用这个。