Re: [whatwg/url] Proposal of .toString({ concise: true }) for nicer output with empty values (#469)

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/469#issuecomment-1975170961
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/url/issues/469/1975170961@github.com>

Received on Sunday, 3 March 2024 13:50:45 UTC