0

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?

4
  • What's keeping you? Commented Jul 3, 2016 at 20:26
  • 1
    Use split("&") and split("=") to do this work. Commented Jul 3, 2016 at 20:26
  • 1
    Possible duplicate of Get url parameter jquery Or How to Get Query String Values In js Commented Jul 3, 2016 at 20:28
  • Forgot so say that the number of names/values is variable. So name3/value3 etc. ... I don´t know how the loop could work Commented Jul 3, 2016 at 20:31

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! What if there are more names/values? (e.g. name3, value3, name4, ...)
Everything above works, but how can I remove the "SKU": in line 4? My string already includes "SKU"
You can don't insert it value to object like this

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.