Analysis URL with arrays in javascript

I have an input url from a GET method in the following format

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

I am trying to parse it with the following code:

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, " "));
                }

but when I pass the myInputs_1function, it returns null.

I somehow plan to generate output in the format:

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

but I cannot extract individual values. Is there a way to achieve the desired result?

edit_1

I have learned that %5Bthere is [, and %5Dis ], but even if I pass myInput_1[]as a parameter, it still returns null, I have no idea why

+4
source share
3 answers

while .exec to . , .

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

, .

+1

URLSearchParams URL :

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"]
+2

Not a regular way

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

Source: https://habr.com/ru/post/1687309/


All Articles