ljharb / qs

A querystring parser with nesting support
BSD 3-Clause "New" or "Revised" License
8.54k stars 728 forks source link

qs.stringify does not respect the addQueryPrefix param when the result of stringify is an empty string #418

Open ehab-cl opened 3 years ago

ehab-cl commented 3 years ago

Hey, thank you for the amazing library.

The following will return an empty string which i think is unexpected qs.stringify({}, { addQueryPrefix: true }) i would expect the previous to return "?"

The use case is for many navigating methods including the native replaceState in window.history they discard an empty string while "?" means to empty the url query params.

I have noticed that this change was introduced in this commit https://github.com/ljharb/qs/commit/229b0e9d38f18ccf37733d117114b8d3cabb8688#diff-0b54a0fe4e28dd7c969fecd6711539ca19dcd5cc1e19a175193d805468d863caL208, previously it would work as expected.

ljharb commented 3 years ago

Yes, imo it would be incorrect to produce a ? when there's nothing in the string; see #213. You can do qs.stringify({}, { addQueryPrefix: true }) || '?' pretty easily if that's something you want.

ehab-cl commented 3 years ago

@ljharb Thanks for the reply. Yea what you suggested is what i already did in my code. But i still think it is worth adding in documentation that addQueryPrefix does not work when stringify produces empty string.

Still i think the way the option is called does not give any indicator that query prefix won't be added when the result is an empty string , and one can do something like the following if not interested in getting just a question mark without anything.

// lodash isEmpty and assuming that params has no undefined values 
isEmpty(params) ? "" : qs.stringify(params, { addQueryPrefix: true })
ljharb commented 3 years ago

I'm fine adding it to the docs.