Treat a query string as structured input

A filter URL is more than a string appended after a question mark. It contains keys, values, possible duplicates and encoding rules. Using URL and URLSearchParams makes those parts explicit. Start with an agreed contract for names and defaults so that browser state, shared links and server interpretation describe the same filtering operation.

Suppose a journal supports category=React and search=state updates. Create a URL from a known base, then set those search parameters. The browser handles encoding of the space and other reserved characters. Avoid manually concatenating an unescaped search term, which can accidentally introduce a new parameter if the visitor types an ampersand or equals sign.

Decide whether a key can repeat

A single category can use set, while multiple selected tags may need append and getAll. Calling get returns one value, not the entire repeated collection. For an example with tag=css and tag=accessibility, decide whether the server expects two keys, one comma-separated value or another format. None of those contracts can be inferred from the visual checkbox list alone.

Validate values after decoding

URLSearchParams handles representation, not application rules. A page parameter still needs to be a positive integer within the supported range. A sort value should come from an allowed set. Do not use a query value directly as an unrestricted redirect destination or HTML fragment. Keep invalid and unsupported input behavior deliberate and consistent.

Make navigation state predictable

When changing a filter, preserve unrelated parameters only if the feature requires them. Reset page numbers when a new query changes the result set. Choose pushState for meaningful history steps and replacement for edits that should not create dozens of Back-button stops. Shareable state should also be reflected in the controls when a saved link is opened.

Check encoded and repeated cases

Try values containing plus signs, spaces, ampersands, Unicode and percent symbols. Verify repeated keys, an empty value and a missing key independently. Copy the finished URL into a new tab and confirm that it reconstructs the same screen. A query-string helper is successful when links behave consistently across reload, sharing and browser navigation.

Further reading

Put the idea to work.

Explore free browser tools for images, text and developer workflows.

Try a free tool