|
1 | 1 | function parseQueryString(queryString) { |
2 | 2 | const queryParams = {}; |
| 3 | + |
| 4 | + // If the query string is empty, return an empty object |
3 | 5 | if (queryString.length === 0) { |
4 | 6 | return queryParams; |
5 | 7 | } |
| 8 | + |
| 9 | + // Split the query string into separate key-value pairs |
6 | 10 | const keyValuePairs = queryString.split("&"); |
7 | 11 |
|
8 | 12 | 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 | + } |
11 | 48 | } |
12 | 49 |
|
13 | 50 | return queryParams; |
|
0 commit comments