0

I want to build a function that parses the URL query string (parameters and values) out of the current URL (e.g. document.location) and stores each key value pair (parameter=value) as an individual element within an array.

So for example, if the URL is: http://example.com?product=shoes&price=59.99&color=red

Then it returns: parameters = ["product=shoes","price=59.99",”color=red"];

Any suggestions?

Thanks,

4
  • Do you really just want strings like "name=value" in your array? Or do you want actual object values that can be referenced? Commented Apr 27, 2018 at 17:47
  • location.href.split('?')[1].split('&') Commented Apr 27, 2018 at 17:47
  • Just the strings, but i want the array to have a name that can be referenced. Also I want to function to have a name. Commented Apr 27, 2018 at 18:00
  • If you're using location.href you could use location.search.slice(1).split('&') instead. Commented Apr 27, 2018 at 18:00

2 Answers 2

1

Depending on your browser requirements, you can use the URLSearchParams object:

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

var params = new URLSearchParams(location.search);

Or if you need to do it manually, you can split the location.search string:

var qs = location.search.replace('?', '');  // get querystring and remove question marks
var pairs = qs.split('&');                  // split on ampersand
var items = {};                             // declare object to store key/value pairs

// Loop through pairs and extract the key and the value (and append them to the object)
for (var i = 0; i < pairs.length; i++) {
    items[pairs[i].split('=')[0]] = pairs[i].split('=')[1];
}

console.log(items);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use .slice() and .split() methods of String:

let str = 'http://example.com?product=shoes&price=59.99&color=red';

let parser = url => url.slice(url.indexOf('?') + 1).split('&');
               
console.log(parser(str));

You can also create an object with key/value pairs by using .reduce():

let str = 'http://example.com?product=shoes&price=59.99&color=red';

let parser = url => url.slice(url.indexOf('?') + 1)
                       .split('&')
                       .reduce((a, c) => {
                         let [key, value] = c.split('=');
                         a[key] = value;
                         return a;
                       }, {});

console.log(parser(str));

Docs:

3 Comments

Thanks, this is great. But how do I give a name to the function, and to the array?
This is problematic for urls with a fragment identifier #
@Evert Yes, you are right but my answer is specific to the format mentioned by OP.

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.