query-string icon indicating copy to clipboard operation
query-string copied to clipboard

Suggest standard URLSearchParams alternative in README

Open silverwind opened this issue 3 years ago • 6 comments

The URL standard includes the URLSearchParams interface which in many cases should be able to replace this module. I think it should be suggested as an alternative.

> String(new URLSearchParams({a: 1, b: 2}))
'a=1&b=2'
> Object.fromEntries(new URLSearchParams('a=1&b=2'))
{ a: '1', b: '2' }

silverwind avatar Feb 05 '21 12:02 silverwind

I agree. I've been thinking about this. I don't think it's useful to just link to it though. We should explain in detail how it differs and their trade-offs.

sindresorhus avatar Feb 05 '21 12:02 sindresorhus

I recently wrote an article detailing the differences between query-string and URLSearchParams. Not sure if it's in-depth enough but it might be useful?

https://dev.to/nerdyman/replacing-query-string-with-native-urlsearchparams-4kdg

Edit: There's also a CodeSandbox demo https://tflmb.csb.app/

nerdyman avatar Feb 12 '21 16:02 nerdyman

It's been a year. Maybe it would help to point to this issue in the README and leave it up to the developer to decide if they want to use the standard object?

This module is extremely popular. Given that, many devs may automatically use this module without even knowing there's a built-in alternative. I've been doing web dev for 10+ years and had no idea either. Was just about to install this module when I randomly found some reference to URLSearchParams.

The even more popular querystring package deprecated itself in favor of URLSearchParams.

tredondo avatar Apr 06 '22 17:04 tredondo

A bonus point for using URLSearchParams instead is that the fetch api and some other http libs will automatically insert the correct content-type header automatically when using URLSearchParams as a body... something that the dev article don't mention

jimmywarting avatar Apr 06 '22 17:04 jimmywarting

Thanks I have merged the documentation update 😊

jasonsaayman avatar May 03 '22 17:05 jasonsaayman

Note: It's not a compatible replacement as space is stringified differently.

> (await import("query-string")).stringify({"foo bar": "bar foo"})
'foo%20bar=bar%20foo'
> String(new URLSearchParams({"foo bar": "bar foo"}))
'foo+bar=bar+foo'

The URLSearchParams recognizes , + and %20 as a space character, but the toString behaviour seems to prefer encoding them as +. This encoding of a space is even inconsistent with other browser APIs:

> encodeURIComponent(" ")
'%20'

So it's certainly not without pitfalls to switch to URLSearchParams.

silverwind avatar Jul 05 '22 14:07 silverwind