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
47 lines (37 loc) · 1.16 KB
/
Copy pathquerystring.js
File metadata and controls
47 lines (37 loc) · 1.16 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
/**
* parseQueryString()
*
* Parses a query string into an object of key-value pairs.
*
* Example:
* parseQueryString("name=Richard&city=Sheffield")
* returns { name: "Richard", city: "Sheffield" }
*/
function parseQueryString(queryString) {
const queryParams = {};
// Return an empty object if the input is an empty string
if (typeof queryString !== "string" || queryString.length === 0) {
return queryParams;
}
// Split the full query string into key-value pairs
const keyValuePairs = queryString.split("&");
for (const pair of keyValuePairs) {
// Skip empty pairs, for example from a trailing "&"
if (pair === "") {
continue;
}
// Find the position of the first "="
const separatorIndex = pair.indexOf("=");
// If there is no "=" sign, treat it as a key with an empty value
if (separatorIndex === -1) {
queryParams[pair] = "";
continue;
}
// Extract the key and everything after the first "=" as the value
const key = pair.slice(0, separatorIndex);
const value = pair.slice(separatorIndex + 1);
queryParams[key] = value;
}
return queryParams;
}
module.exports = parseQueryString;