|
1 | 1 | function parseQueryString(queryString) { |
2 | 2 | const queryParams = {}; |
3 | | - if (queryString.length === 0) { |
| 3 | + |
| 4 | + if (!queryString || queryString.length === 0) { |
4 | 5 | return queryParams; |
5 | 6 | } |
| 7 | + |
| 8 | + // Helper to decode '+' as spaces and percent-encoded characters |
| 9 | + function decodeParam(str) { |
| 10 | + return decodeURIComponent(str.replace(/\+/g, " ")); |
| 11 | + } |
| 12 | + |
| 13 | + // Split by '&' to get raw key-value pairs |
6 | 14 | const keyValuePairs = queryString.split("&"); |
7 | 15 |
|
8 | 16 | for (const pair of keyValuePairs) { |
9 | | - const [key, value] = pair.split("="); |
10 | | - queryParams[key] = value; |
| 17 | + // Ignore empty pairs caused by trailing or duplicate '&' (e.g. "a=1&&b=2&") |
| 18 | + if (pair.length === 0) { |
| 19 | + continue; |
| 20 | + } |
| 21 | + |
| 22 | + let rawKey, rawValue; |
| 23 | + const equalIndex = pair.indexOf("="); |
| 24 | + |
| 25 | + if (equalIndex === -1) { |
| 26 | + // Key with no '=' (e.g., "key") -> value is empty string |
| 27 | + rawKey = pair; |
| 28 | + rawValue = ""; |
| 29 | + } else { |
| 30 | + // Split on the FIRST '=' only (handles values containing '=', e.g. "a=b-2") |
| 31 | + rawKey = pair.slice(0, equalIndex); |
| 32 | + rawValue = pair.slice(equalIndex + 1); |
| 33 | + } |
| 34 | + |
| 35 | + const key = decodeParam(rawKey); |
| 36 | + const value = decodeParam(rawValue); |
| 37 | + |
| 38 | + // Stretch Goal: Handle duplicate keys by converting to an array |
| 39 | + if (Object.prototype.hasOwnProperty.call(queryParams, key)) { |
| 40 | + if (Array.isArray(queryParams[key])) { |
| 41 | + queryParams[key].push(value); |
| 42 | + } else { |
| 43 | + queryParams[key] = [queryParams[key], value]; |
| 44 | + } |
| 45 | + } else { |
| 46 | + queryParams[key] = value; |
| 47 | + } |
11 | 48 | } |
12 | 49 |
|
13 | 50 | return queryParams; |
|
0 commit comments