Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the URL constructor encode brackets in query strings?

Tags:

javascript

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}
like image 916
Luke Avatar asked Jan 01 '26 20:01

Luke


1 Answers

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.

like image 179
Evert Avatar answered Jan 03 '26 10:01

Evert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!