URI 错误:格式错误的 URI 序列

当 URI 编码或解码不成功时,会出现 JavaScript 异常 "格式错误的 URI 序列"。

¥The JavaScript exception "malformed URI sequence" occurs when URI encoding or decoding wasn't successful.

信息

¥Message

URIError: URI malformed (V8-based)
URIError: malformed URI sequence (Firefox)
URIError: String contained an illegal UTF-16 sequence. (Safari)

错误类型

¥Error type

URIError

什么地方出了错?

¥What went wrong?

URI 编码或解码不成功。给 decodeURIencodeURIencodeURIComponentdecodeURIComponent 函数的参数无效,因此该函数无法正确编码或解码。

¥URI encoding or decoding wasn't successful. An argument given to either the decodeURI, encodeURI, encodeURIComponent, or decodeURIComponent function was not valid, so that the function was unable encode or decode properly.

示例

¥Examples

编码

¥Encoding

编码将某些字符的每个实例替换为表示字符的 UTF-8 编码的一个、两个、三个或四个转义序列。如果尝试对不属于高低对一部分的代理项进行编码,则会抛出 URIError,例如:

¥Encoding replaces each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. An URIError will be thrown if there is an attempt to encode a surrogate which is not part of a high-low pair, for example:

js
encodeURI("\uD800");
// "URIError: malformed URI sequence"

encodeURI("\uDFFF");
// "URIError: malformed URI sequence"

高低对就可以了。例如:

¥A high-low pair is OK. For example:

js
encodeURI("\uD800\uDFFF");
// "%F0%90%8F%BF"

解码

¥Decoding

解码将编码的 URI 组件中的每个转义序列替换为其表示的字符。如果没有这样的字符,则会抛出错误:

¥Decoding replaces each escape sequence in the encoded URI component with the character that it represents. If there isn't such a character, an error will be thrown:

js
decodeURIComponent("%E0%A4%A");
// "URIError: malformed URI sequence"

如果输入正确,通常应该如下所示:

¥With proper input, this should usually look like something like this:

js
decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
// "JavaScript_шеллы"

也可以看看