DEV Community

Soren Sterling
Soren Sterling

Posted on

A small thing about URLSearchParams

Some URLs have the same query parameter more than once.

For example:

/products?tag=javascript&tag=css
Enter fullscreen mode Exit fullscreen mode

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"));
Enter fullscreen mode Exit fullscreen mode

This prints:

javascript
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

append() adds another value, even if the key already exists.

But set() works differently:

params.set("tag", "react");

console.log(params.toString());
// tag=react
Enter fullscreen mode Exit fullscreen mode

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)