Practical developer guides
Parse query parameters: repeated keys, empty values and fragments
Preserve repeated parameters and distinguish URL query data from a fragment that is not sent in HTTP requests.
Parse the URL before the query
The query begins after ? and ends before #. A fragment is handled by the client and is not sent as part of the HTTP request target.
Use URL Parser to identify those parts, then inspect query parameters. Do not split an entire URL on every question mark or ampersand.
https://example.com/search?tag=go&tag=json&q=#results
Query: tag=go&tag=json&q=
Fragment: resultsRepeated keys can be intentional
A query can contain the same key multiple times. get returns one value while getAll returns all values under URLSearchParams behavior.
Converting directly to an object can erase repetition. Check whether the API expects repeated keys, comma-separated text or a JSON-encoded array.
new URLSearchParams("tag=go&tag=json").getAll("tag")
→ ["go","json"]Empty does not necessarily mean missing
Under common query parsing, q and q= both produce an empty value, while no q parameter is absent. APIs may define different business meaning for those cases.
Use has to test presence separately from get. Do not default an empty value away when it deliberately means clearing a filter.
Build from raw values
Pass unencoded names and values to URLSearchParams; it performs encoding during serialization. Literal plus signs and ampersands need that handling.
Round-trip a query containing Unicode, repeated keys and an empty value. Keep authentication data out of URLs where the protocol provides a safer header mechanism.