在JavaScript中,当方括号和圆括号位于查询字符串中时,URL
构造函数不会对它们进行编码,而AS encodeURI
或encodeURIComponent
总是对它们进行编码.这让我很困惑,因为大多数消息来源说,当查询参数包含特殊字符时,要使用encodeURI
/encodeURIComponent
进行编码.我预计URL
号物体也会有类似的行为.
这导致我在编写单元测试时遇到问题,因为我不知道来自URL对象的查询参数将如何编码.这有规范吗?或者我应该总是在使用URL
构造函数之前只编码我的参数吗?谢谢你的帮助.
显示URL对象未对查询字符串中的方括号进行编码的示例
const href = (new URL('https://foobar.com?myQuery={"@asdf/asdf":"1234"}')).href;
// ^ https://foobar.com/?myQuery={%22@asdf/asdf%22:%221234%22}
如果我使用encodeURI
,唯一的区别是方括号是编码的
const href = encodeURI('https://foobar.com?myQuery={"@asdf/asdf":"1234"}');
// ^ https://foobar.com?myQuery=%7B%22@asdf/asdf%22:%221234%22%7D
注意:如果方括号不在查询参数中,则URL对象does对它们进行编码.
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}