decodeURI、decodeURIComponent、encodeURI、encodeURIComponent是什么?
decodeURI()
: 解码使用 encodeURI()
编码的统一资源标识符(URI)。
decodeURIComponent()
: 解码使用 encodeURIComponent()
编码的统一资源标识符(URI)组件。
encodeURI()
: 对统一资源标识符(URI)进行编码,以便将其作为 URL 的一部分进行传输。
encodeURIComponent()
: 对统一资源标识符(URI)组件进行编码,以便将其作为 URL 参数进行传输。
这些函数与 URL 编码和解码有关。URL 编码是一种将特殊字符(如空格、标点符号等)转换为 URL 可以安全传输的格式的过程。URL 编码通常用于在查询字符串或其他 URL 组件中包含特殊字符。
以下是这些函数的详细解释:
encodeURI()
: 这个函数用于对整个 URI(统一资源标识符)进行编码。它会将特殊字符(如空格、标点符号等)转换为其对应的百分号编码(%XY,其中 XY 是字符的 ASCII 码的十六进制表示)。然而,它不会对某些具有特殊含义的 URL 组件(如冒号、正斜杠等)进行编码。
示例:
const uri = "https://example.com/测试 页面";
const encodedURI = encodeURI(uri);
console.log(encodedURI); // 输出:"https://example.com/%E6%B5%8B%E8%AF%95%20%E9%A1%B5%E9%9D%A2"
encodeURIComponent()
: 这个函数用于对 URI 的单个组件(如查询字符串参数)进行编码。它会将所有特殊字符(包括具有特殊含义的 URL 组件,如冒号、正斜杠等)转换为百分号编码。
示例:
const uriComponent = "测试=测试 页面";
const encodedURIComponent = encodeURIComponent(uriComponent);
console.log(encodedURIComponent); // 输出:"测试%3D%E6%B5%8B%E8%AF%95%20%E9%A1%B5%E9%9D%A2"
decodeURI()
: 这个函数用于对使用encodeURI()
编码的整个 URI 进行解码。它将百分号编码的字符转换回原始字符。
示例:
const encodedURI = "https://example.com/%E6%B5%8B%E8%AF%95%20%E9%A1%B5%E9%9D%A2";
const decodedURI = decodeURI(encodedURI);
console.log(decodedURI); // 输出:"https://example.com/测试 页面"
decodeURIComponent()
: 这个函数用于对使用encodeURIComponent()
编码的 URI 组件进行解码。它将百分号编码的字符转换回原始字符。
示例:
const encodedURIComponent = "测试%3D%E6%B5%8B%E8%AF%95%20%E9%A1%B5%E9%9D%A2";
const decodedURIComponent = decodeURIComponent(encodedURIComponent);
console.log(decodedURIComponent); // 输出:"测试=测试 页面"
在处理包含特殊字符的 URL 时,这些函数非常有用,可以确保 URL 的正确传输和解析。在实际开发中,我们通常使用 encodeURIComponent()
对 URL 的参数进行编码,以防止 URL 解析出现问题。