Some URLs have the same query parameter more than once.
For example:
/products?tag=javascript&tag=css
This is pretty normal for things like filters, where someone can select multiple options.
But there's a small detail with URLSearchParams that is easy to miss.
const params = new URLSearchParams(
"tag=javascript&tag=css"
);
console.log(params.get("tag"));
This prints:
javascript
Not an array, and not the last value. Just the first one.
If you want all the values, there's a separate method:
console.log(params.getAll("tag"));
// ["javascript", "css"]
Another thing worth knowing is the difference between set() and append().
const params = new URLSearchParams();
params.append("tag", "javascript");
params.append("tag", "css");
console.log(params.toString());
// tag=javascript&tag=css
append() adds another value, even if the key already exists.
But set() works differently:
params.set("tag", "react");
console.log(params.toString());
// tag=react
It replaces the value and removes the other entries with the same key.
This can matter when updating search filters. If the user selects another category and you use set() when you meant append(), the previous selections disappear from the URL.
There's nothing wrong with either method. They just do different things.
I think URLSearchParams is quite handy compared with manually building query strings, especially since it handles URL encoding for you.
Just remember that a query parameter doesn't necessarily have only one value.
Top comments (0)