使用JavaScript解析带有数组的URL

3

我已经以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_1传递给函数时,它返回null。

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

myInput_1 = ['things', 'are', 'working']
myInput_2 = ['i', 'hope']
myInput_3 = ['so']

但我无法提取个别的值。有没有一种方法可以实现所需的输出?

编辑_1

我学到%5B[%5D],但即使我将myInput_1[]作为参数传递给函数,它仍然返回null,我不知道为什么。

3个回答

2
你可以使用URL实例的URLSearchParams对象:
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"]

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

1
在使用.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的答案。


0

非正则表达式方式

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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接