Skip to content

Commit dc4e5b1

Browse files
committed
add querystring
.js
1 parent 79517e9 commit dc4e5b1

1 file changed

Lines changed: 39 additions & 2 deletions

File tree

‎Sprint-2/implement/querystring.js‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,50 @@
11
function parseQueryString(queryString) {
22
const queryParams = {};
3+
4+
// If the query string is empty, return an empty object
35
if (queryString.length === 0) {
46
return queryParams;
57
}
8+
9+
// Split the query string into separate key-value pairs
610
const keyValuePairs = queryString.split("&");
711

812
for (const pair of keyValuePairs) {
9-
const [key, value] = pair.split("=");
10-
queryParams[key] = value;
13+
// Ignore empty pairs
14+
if (pair === "") {
15+
continue;
16+
}
17+
18+
// Find the first "="
19+
const equalsPosition = pair.indexOf("=");
20+
21+
let key;
22+
let value;
23+
24+
// If there is no "="
25+
if (equalsPosition === -1) {
26+
key = pair;
27+
value = "";
28+
} else {
29+
// Everything before "=" is the key
30+
key = pair.substring(0, equalsPosition);
31+
32+
// Everything after the first "=" is the value
33+
value = pair.substring(equalsPosition + 1);
34+
}
35+
36+
// Replace "+" with spaces and decode special characters
37+
key = decodeURIComponent(key.replace(/\+/g, " "));
38+
value = decodeURIComponent(value.replace(/\+/g, " "));
39+
40+
// If the key already exists, store multiple values in an array
41+
if (queryParams[key] === undefined) {
42+
queryParams[key] = value;
43+
} else if (Array.isArray(queryParams[key])) {
44+
queryParams[key].push(value);
45+
} else {
46+
queryParams[key] = [queryParams[key], value];
47+
}
1148
}
1249

1350
return queryParams;

0 commit comments

Comments
 (0)