Re: [whatwg/url] searchParams.set("param", undefined) should not stringify as param=undefined (#427)

For anyone looking for a userland solution for this, this is what we ended up with:

```ts
function setQueryParam(queryParamName: string, queryParamValue: number | undefined) {
  let queryString;

  const newSearchParams = new URLSearchParams(window.location.search);

  if (typeof queryParamValue === 'undefined') {
    newSearchParams.set(queryParamName, '');
    queryString = newSearchParams.toString().replace(
      new RegExp(`${queryParamName}=`),
      queryParamName,
    );
  } else {
    newSearchParams.set(queryParamName, String(queryParamValue));
    queryString = newSearchParams.toString();
  }

  const newUrl = `${window.location.origin}${window.location.pathname}?${queryString}`;

  return newUrl;
}
```

Usage:

```ts
setQueryParam('a', 'b'); // 'https://github.com/whatwg/url/issues/469?a=b'
setQueryParam('a', undefined); // 'https://github.com/whatwg/url/issues/469?a'
```

-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/url/issues/427#issuecomment-1975171021
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/url/issues/427/1975171021@github.com>

Received on Sunday, 3 March 2024 13:51:00 UTC