这些函数都是 JavaScript 中用于 URI(统一资源标识符)编码和解码的方法。它们的作用是在 URL 中对特定字符进行转义或解码,以确保它们在传输过程中不会被误解或丢失。
以下是它们之间的区别:
-
encodeURI
:encodeURI
用于对整个 URI 进行编码,包括协议、域名、路径和查询参数等。- 不会对特殊字符
; , / ? : @ & = + $ #
进行编码,以保留其在 URI 中的含义。 - 只会对其他非 ASCII 字符(Unicode 字符)进行编码。
-
encodeURIComponent
:encodeURIComponent
用于对 URI 中的查询参数进行编码。- 会对除了字母、数字和特殊字符
- _ . ! ~ * ' ( )
之外的所有字符进行编码。
-
decodeURI
:decodeURI
用于对整个 URI 进行解码,与encodeURI
对应。- 对使用
encodeURI
编码的所有字符进行解码,包括非 ASCII 字符。
-
decodeURIComponent
:decodeURIComponent
用于对 URI 中的查询参数进行解码,与encodeURIComponent
对应。- 对使用
encodeURIComponent
编码的所有字符进行解码,包括特殊字符。
使用示例:
const uri = 'https://example.com/path/to/file.html?key=value&name=John Doe';
const encodedURI = encodeURI(uri);
console.log(encodedURI);
// 输出:https://example.com/path/to/file.html?key=value&name=John%20Doe
const encodedComponent = encodeURIComponent(uri);
console.log(encodedComponent);
// 输出:https%3A%2F%2Fexample.com%2Fpath%2Fto%2Ffile.html%3Fkey%3Dvalue%26name%3DJohn%20Doe
const decodedURI = decodeURI(encodedURI);
console.log(decodedURI);
// 输出:https://example.com/path/to/file.html?key=value&name=John Doe
const decodedComponent = decodeURIComponent(encodedComponent);
console.log(decodedComponent);
// 输出:https://example.com/path/to/file.html?key=value&name=John Doe