decodeURI()

decodeURI() 函数对先前由 encodeURI() 或类似例程创建的统一资源标识符 (URI) 进行解码。

¥The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by encodeURI() or a similar routine.

Try it

语法

¥Syntax

js
decodeURI(encodedURI)

参数

¥Parameters

encodedURI

完整的、编码的统一资源标识符。

返回值

¥Return value

表示给定编码统一资源标识符 (URI) 的未编码版本的新字符串。

¥A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI).

例外情况

¥Exceptions

URIError

如果 encodedURI 包含 % 且后面没有两个十六进制数字,或者转义序列未编码有效的 UTF-8 字符,则抛出该错误。

描述

¥Description

decodeURI() 是全局对象的函数属性。

¥decodeURI() is a function property of the global object.

decodeURI() 函数通过将 %XX 形式的每个转义序列视为一个 UTF-8 代码单元(一个字节)来解码 URI。在 UTF-8 中,第一个字节中前导 1 位的数量,可以是 0(对于 1 字节 ASCII 字符)、2、3 或 4,表示字符中的字节数。因此,通过读取第一个转义序列,decodeURI() 可以确定还要消耗多少个转义序列。如果 decodeURI() 无法找到预期数量的序列,或者转义序列未编码有效的 UTF-8 字符,则会抛出 URIError

¥The decodeURI() function decodes the URI by treating each escape sequence in the form %XX as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte ASCII characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, decodeURI() can determine how many more escape sequences to consume. If decodeURI() fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a URIError is thrown.

decodeURI() 解码所有转义序列,但如果转义序列编码以下字符之一,则转义序列将保留在输出字符串中(因为它们是 URI 语法的一部分):

¥decodeURI() decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax):

; / ? : @ & = + $ , #

示例

¥Examples

解码西里尔字母 URL

¥Decoding a Cyrillic URL

js
decodeURI(
  "https://web.nodejs.cn/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B",
);
// "https://web.nodejs.cn/ru/docs/JavaScript_шеллы"

decodeURI() vs. decodeURIComponent()

decodeURI() 假定输入是完整的 URI,因此它不会解码属于 URI 语法一部分的字符。

¥decodeURI() assumes the input is a full URI, so it does not decode characters that are part of the URI syntax.

js
decodeURI(
  "https://web.nodejs.cn/docs/JavaScript%3A%20a_scripting_language",
);
// "https://web.nodejs.cn/docs/JavaScript%3A a_scripting_language"

decodeURIComponent(
  "https://web.nodejs.cn/docs/JavaScript%3A%20a_scripting_language",
);
// "https://web.nodejs.cn/docs/JavaScript: a_scripting_language"

捕获错误

¥Catching errors

js
try {
  const a = decodeURI("%E0%A4%A");
} catch (e) {
  console.error(e);
}

// URIError: malformed URI sequence

规范

Specification
ECMAScript Language Specification
# sec-decodeuri-encodeduri

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看