3

I have input url from 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 myInputs_1 to the function, it returns null.

I somehow plan on generating the output in the format:

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

but I am not able to extract the individual values. Is there a way to achieve the desired output?

edit_1

I learned that %5B is [ and %5D is ], but even if I pass myInput_1[] as parameter to the function, it still returns null, I have no idea why

3 Answers 3

2

You could use the URLSearchParams object of a URL instance:

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

your answer is really concise, but I have a browser compatibility requirement. In future, if possible, people should use this.
1

You need to do a while loop when using .exec to find successive matches. Also, I simplified your regex.

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

I suggest you go with Jean's answer unless you browser compatibility matters to you.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.