Skip to content

Commit

Permalink
doc: doc and test URLSearchParams discrepancy
Browse files Browse the repository at this point in the history
The WHATWG URL spec is not going to change this behavior so
let's document it

Signed-off-by: James M Snell <[email protected]>

Fixes: #33037

PR-URL: #33236
Reviewed-By: Luigi Pinca <[email protected]>
Reviewed-By: Rich Trott <[email protected]>
Reviewed-By: Joyee Cheung <[email protected]>
Reviewed-By: Zeyu Yang <[email protected]>
  • Loading branch information
jasnell authored and codebytere committed May 7, 2020
1 parent cf47698 commit 25443fa
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
24 changes: 21 additions & 3 deletions doc/api/url.md
Original file line number Diff line number Diff line change
Expand Up @@ -472,9 +472,27 @@ and [`url.format()`][] methods would produce.
* {URLSearchParams}

Gets the [`URLSearchParams`][] object representing the query parameters of the
URL. This property is read-only; to replace the entirety of query parameters of
the URL, use the [`url.search`][] setter. See [`URLSearchParams`][]
documentation for details.
URL. This property is read-only but the `URLSearchParams` object it provides
can be used to mutate the URL instance; to replace the entirety of query
parameters of the URL, use the [`url.search`][] setter. See
[`URLSearchParams`][] documentation for details.

Use care when using `.searchParams` to modify the `URL` because,
per the WHATWG specification, the `URLSearchParams` object uses
different rules to determine which characters to percent-encode. For
instance, the `URL` object will not percent encode the ASCII tilde (`~`)
character, while `URLSearchParams` will always encode it:

```js
const myUrl = new URL('https://example.org/abc?foo=~bar');

console.log(myUrl.search); // prints ?foo=~bar

// Modify the URL via searchParams...
myUrl.searchParams.sort();

console.log(myUrl.search); // prints ?foo=%7Ebar
```

#### `url.username`

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,12 @@ const URLSearchParams = require('url').URLSearchParams;
message: 'Value of "this" must be of type URLSearchParams'
});
}

// The URLSearchParams stringifier mutates the base URL using
// different percent-encoding rules than the URL itself.
{
const myUrl = new URL('https://example.org?foo=~bar');
assert.strictEqual(myUrl.search, '?foo=~bar');
myUrl.searchParams.sort();
assert.strictEqual(myUrl.search, '?foo=%7Ebar');
}

0 comments on commit 25443fa

Please sign in to comment.