|
1 | 1 | function parseQueryString(queryString) { |
2 | | - const queryParams = {}; |
3 | | - if (queryString.length === 0) { |
4 | | - return queryParams; |
| 2 | + const result = {}; |
| 3 | + |
| 4 | + // Return empty object for empty or non-string inputs |
| 5 | + if (typeof queryString !== "string" || !queryString.trim()) { |
| 6 | + return result; |
5 | 7 | } |
6 | | - const keyValuePairs = queryString.split("&"); |
7 | 8 |
|
8 | | - for (const pair of keyValuePairs) { |
9 | | - const [key, value] = pair.split("="); |
10 | | - queryParams[key] = value; |
| 9 | + // Optional: strip leading '?' if passed a full URL search string (e.g., "?a=1") |
| 10 | + const sanitizedInput = queryString.startsWith("?") |
| 11 | + ? queryString.slice(1) |
| 12 | + : queryString; |
| 13 | + |
| 14 | + // Split pairs by '&' |
| 15 | + const pairs = sanitizedInput.split("&"); |
| 16 | + |
| 17 | + for (const pair of pairs) { |
| 18 | + // Ignore empty pairs (e.g. from consecutive '&&' or trailing '&') |
| 19 | + if (!pair) continue; |
| 20 | + |
| 21 | + // Find the FIRST '=' to separate key and value correctly |
| 22 | + const equalIndex = pair.indexOf("="); |
| 23 | + |
| 24 | + let rawKey = ""; |
| 25 | + let rawValue = ""; |
| 26 | + |
| 27 | + if (equalIndex === -1) { |
| 28 | + // Key with no '=' (e.g., "key" -> key="key", value="") |
| 29 | + rawKey = pair; |
| 30 | + rawValue = ""; |
| 31 | + } else { |
| 32 | + // Split strictly on the first '=' so values containing '=' stay intact |
| 33 | + rawKey = pair.slice(0, equalIndex); |
| 34 | + rawValue = pair.slice(equalIndex + 1); |
| 35 | + } |
| 36 | + |
| 37 | + // Helper to decode query string encoding (+ to space, percent-encoding) |
| 38 | + const decodeParam = (str) => { |
| 39 | + try { |
| 40 | + return decodeURIComponent(str.replace(/\+/g, " ")); |
| 41 | + } catch { |
| 42 | + // Fallback if URI decoding fails on malformed input |
| 43 | + return str.replace(/\+/g, " "); |
| 44 | + } |
| 45 | + }; |
| 46 | + |
| 47 | + const key = decodeParam(rawKey); |
| 48 | + const value = decodeParam(rawValue); |
| 49 | + |
| 50 | + // Handle single key vs duplicate keys |
| 51 | + if (Object.prototype.hasOwnProperty.call(result, key)) { |
| 52 | + if (Array.isArray(result[key])) { |
| 53 | + result[key].push(value); |
| 54 | + } else { |
| 55 | + result[key] = [result[key], value]; |
| 56 | + } |
| 57 | + } else { |
| 58 | + result[key] = value; |
| 59 | + } |
11 | 60 | } |
12 | 61 |
|
13 | | - return queryParams; |
| 62 | + return result; |
14 | 63 | } |
15 | 64 |
|
16 | 65 | module.exports = parseQueryString; |
0 commit comments