In brief
The query parameters can be read and updated as key and value pairs. This avoids many errors when manually gluing addresses.
Useful to know
The part after the question mark in an address often contains query parameters. Through them, the site can present a selected page, a search term, or an order of results. URLSearchParams provides methods for working with these key and value pairs. Instead of the program manually cutting the text into different characters, it can read, add and remove parameters through a specific interface. This makes the intent of the operation easier to recognize when reviewing the code. [1]
The searchParams property of a URL object provides access to the decoded parameters. [2] Methods such as get, getAll, set and append have different tasks. A key may be present more than once, and adding one more value is not the same as replacing the existing one. [1] Before choosing a method, it is useful to describe the contract at the address. Does the filter allow one category or several? Is the repeated key an expected choice, or is it an unwanted input?
Let's look at a fictional exhibition catalog. The visitor selects a city and a theme, and then copies a friend's address. The desired behavior can be described without program code: when opening the copied address, the same filters are restored. This gives a clear task for the parameters. For verification, we can use a city with a namespace, an empty search word, and more than one topic. This shows whether the address represents the choice consistently and comprehensible.
Character encoding is another reason not to rely on manual gluing. URLSearchParams serializes values according to certain rules, and the spaces can be represented by a plus sign . [1] MDN notes that when updated by searchParams, the text representation of URL can change even when the values look the same. [2] Therefore, the comparison of addresses must be consistent with the purpose: do we care about the literal text or the meanings of the specific parameters?
When testing the filter, it is also useful to check what happens to the parameters that we do not change. If the visitor changes the subject, should the chosen city remain? If a new search starts, is the previous page number saved? These are solutions of the application that the parameter interface does not take automatically. Well-described expectations prevent situations where a technically valid address presents an unexpected combination of choices.
A completed check can go through creating an address, opening in a new tab, and re-changing the filter. For each step, we compare the visible controls with the displayed results. Thus, the parameters become a verifiable contract between the address and the page. URLSearchParams facilitates text processing, and the quality of the function depends on the clear meaning of keys, allowable values, and behavior in missing or repeated parameters.
Sources
For further detail and to check the information: