-
Notifications
You must be signed in to change notification settings - Fork 1
/
getQueryParams.js
50 lines (43 loc) · 1.03 KB
/
getQueryParams.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
var getQueryString = require('./getQueryString');
/**
* Gets the query params from the browser URL
* getQueryParams() returns a query object
* getQueryParams(key) returns the value of the key in the query
* @param {string} key [optional]
* @return {[type]} [description]
*/
function getQueryParams(url, key) {
var qd = {};
var value;
var source = url ? getQueryString(url) : location.search;
if (!source) {
return;
}
// Based on http://stackoverflow.com/a/21152762/226953
source.split("&").forEach(
function(item) {
var s = item.split("="),
k = s[0],
v = s[1] && decodeURIComponent(s[1]);
(k in qd) ? qd[k].push(v) : qd[k] = [v]
}
);
if (key) {
value = qd[key];
if (!value) {
return;
}
if (value.length === 1) {
return value[0];
}
return value;
}
Object.keys(qd).forEach(function (key) {
var value = qd[key];
if (value && value.length === 1) {
qd[key] = value[0];
}
});
return qd;
}
module.exports = getQueryParams;