forked from CodeYourFuture/Module-Data-Groups
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquerystring.js
More file actions
54 lines (44 loc) · 1.21 KB
/
Copy pathquerystring.js
File metadata and controls
54 lines (44 loc) · 1.21 KB
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
51
52
53
54
/**
* parseQueryString()
*
* Parses a query string into an object of decoded key-value pairs.
*
* Handles:
* - empty strings
* - multiple pairs separated by "&"
* - values containing "="
* - missing values
* - missing "="
* - trailing "&"
* - URL-encoded keys and values
*/
function parseQueryString(queryString) {
const queryParams = Object.create(null);
// Return an empty object if the input is invalid or empty
if (typeof queryString !== "string" || queryString.length === 0) {
return queryParams;
}
const keyValuePairs = queryString.split("&");
for (const pair of keyValuePairs) {
// Skip empty pairs, e.g. from a trailing "&"
if (pair === "") {
continue;
}
const separatorIndex = pair.indexOf("=");
let rawKey;
let rawValue;
// If there is no "=", treat it as a key with an empty value
if (separatorIndex === -1) {
rawKey = pair;
rawValue = "";
} else {
rawKey = pair.slice(0, separatorIndex);
rawValue = pair.slice(separatorIndex + 1);
}
const key = decodeURIComponent(rawKey);
const value = decodeURIComponent(rawValue);
queryParams[key] = value;
}
return queryParams;
}
module.exports = parseQueryString;