In JavaScript, the URL constructor does not encode brackets and parentheses when they are in a query string where as encodeURI or encodeURIComponent always encodes them. This confuses me because most sources say to encode your query params when they contain special characters using encodeURI/encodeURIComponent. I would expect the URL object to have similar behavior.
This causes me problems writing unit tests since I do not know how the query params from the URL object will be encoded. Is there a spec for this or should I always just encode my params before using URL constructor? Thank you for your help.
example showing URL object not encoding brackets in query string
const href = (new URL('https://foobar.com?myQuery={"@asdf/asdf":"1234"}')).href;
// ^ https://foobar.com/?myQuery={%22@asdf/asdf%22:%221234%22}
if I use encodeURI, the only difference is the brackets are encoded
const href = encodeURI('https://foobar.com?myQuery={"@asdf/asdf":"1234"}');
// ^ https://foobar.com?myQuery=%7B%22@asdf/asdf%22:%221234%22%7D
NOTE: The URL object does encode brackets if they are not in a query param.
const href = (new URL('https://foobar.com/}}}?myQuery={"@asdf/asdf":"1234"}')).href;
// ^ https://foobar.com/%7D%7D%7D?myQuery={%22@asdf/asdf%22:%221234%22}
There are multiple encodings possible that all should be interpreted a the same url, so none are technically wrong. Another example is that percent encoding can be done with uppercase or lowercase characters (%aa or %AA), and the domain is case-insensitive and spaces may be encoded (in some parts) as either + or %20.
if you want to unittest a specific URL encoder implmententation you can match strings, but if you want to know if 2 urls are identical regardless of how it was encoded you first need to go through step called 'normalization' before comparison.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With