Reputation: 3
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,
Upvotes: 0
Views: 6838
Reputation: 16675
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);
Upvotes: 1
Reputation: 39322
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:
String.prototype.slice()
String.prototype.indexOf()
String.prototype.split()
Array.prototype.reduce()
Upvotes: 0