user1907132 user1907132 - 5 months ago 21
jQuery Question

How to parse url parameters using javascript

I got these URL parameters:

/?sku=123456 & name1=NAME1 & value1=VALUE1 & name2=NAME2 & value2=VALUE2


I would like to print them out in HTML using javascript/jQuery in this format:

SKU: 123456
NAME1 : VALUE1
NAME2 : VALUE2
(NAME3 : ...)


How does a loop for a variable amount of names/values work?

Answer

You need to use split() to parsing string with & delimiter. First index of result is /?sku=123456. I inserted it into object and remove it from array. Then used for to iterating array element and getting value of every element.

var url = "/?sku=123456 & name1=NAME1 & value1=VALUE1 & name2=NAME2 & value2=VALUE2 ";
var params = url.split("&");
var data = {
    "SKU": params[0].split("=")[1]
};
params.splice(0, 1);

for (var i = 0; i < params.length; i+=2){
    if (i % 2 == 0)
        data[params[i].split("=")[1]] = params[i+1].split("=")[1];
}
console.log(data);