Skip to content

Commit ea3a68f

Browse files
jasnellcodebytere
authored andcommittedJun 7, 2020
doc: doc and test URLSearchParams discrepancy
The WHATWG URL spec is not going to change this behavior so let's document it Signed-off-by: James M Snell <jasnell@gmail.com> Fixes: #33037 PR-URL: #33236 Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com> Reviewed-By: Zeyu Yang <himself65@outlook.com>
1 parent c054834 commit ea3a68f

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed
 

‎doc/api/url.md

+21-3
Original file line numberDiff line numberDiff line change
@@ -472,9 +472,27 @@ and [`url.format()`][] methods would produce.
472472
* {URLSearchParams}
473473

474474
Gets the [`URLSearchParams`][] object representing the query parameters of the
475-
URL. This property is read-only; to replace the entirety of query parameters of
476-
the URL, use the [`url.search`][] setter. See [`URLSearchParams`][]
477-
documentation for details.
475+
URL. This property is read-only but the `URLSearchParams` object it provides
476+
can be used to mutate the URL instance; to replace the entirety of query
477+
parameters of the URL, use the [`url.search`][] setter. See
478+
[`URLSearchParams`][] documentation for details.
479+
480+
Use care when using `.searchParams` to modify the `URL` because,
481+
per the WHATWG specification, the `URLSearchParams` object uses
482+
different rules to determine which characters to percent-encode. For
483+
instance, the `URL` object will not percent encode the ASCII tilde (`~`)
484+
character, while `URLSearchParams` will always encode it:
485+
486+
```js
487+
const myUrl = new URL('https://example.org/abc?foo=~bar');
488+
489+
console.log(myUrl.search); // prints ?foo=~bar
490+
491+
// Modify the URL via searchParams...
492+
myUrl.searchParams.sort();
493+
494+
console.log(myUrl.search); // prints ?foo=%7Ebar
495+
```
478496

479497
#### `url.username`
480498

‎test/parallel/test-whatwg-url-custom-searchparams-stringifier.js

+9
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,12 @@ const URLSearchParams = require('url').URLSearchParams;
1616
message: 'Value of "this" must be of type URLSearchParams'
1717
});
1818
}
19+
20+
// The URLSearchParams stringifier mutates the base URL using
21+
// different percent-encoding rules than the URL itself.
22+
{
23+
const myUrl = new URL('https://example.org?foo=~bar');
24+
assert.strictEqual(myUrl.search, '?foo=~bar');
25+
myUrl.searchParams.sort();
26+
assert.strictEqual(myUrl.search, '?foo=%7Ebar');
27+
}

0 commit comments

Comments
 (0)
Please sign in to comment.