Skip to content

Commit ba22418

Browse files
committed
safe decoding of url encoded strings
1 parent 97848e5 commit ba22418

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

Sprint-2/implement/querystring.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,24 @@ function parseQueryString(queryString) {
55
}
66
const keyValuePairs = queryString.split("&"); // Split by '&' to get individual key-value pairs
77

8+
function safeDecode(str) {
9+
try {
10+
return decodeURIComponent(str);
11+
} catch {
12+
return str; // Return original string if decoding fails
13+
}
14+
}
815
for (const pair of keyValuePairs) {
916
// Iterate over each key-value pair
1017
if (!pair.includes("=")) {
1118
// Handle missing equals sign
12-
queryParams[pair] = undefined; // Assign undefined for keys without equals sign
19+
queryParams[safeDecode(pair)] = undefined; // Assign undefined for keys without equals sign
1320
continue; // Move to the next pair
1421
}
15-
const [key, ...rest] = pair.split("="); // array destructured into key and rest of array.
22+
const [rawKey, ...rest] = pair.split("="); // array destructured into key and rest of array.
1623
// Split by '=' to separate key and value.
1724
const value = rest.join("="); // Join back any '=' in the value using rest operator
18-
queryParams[key] = value; // Assign key-value pair to the result object
25+
queryParams[safeDecode(rawKey)] = safeDecode(value); // Assign key-value pair to the result object
1926
}
2027

2128
return queryParams;

0 commit comments

Comments
 (0)