Skip to content

escape、encodeURI、encodeURIComponent的区别

在 JavaScript 中,escape()encodeURI()encodeURIComponent() 是三个用于编码字符串的函数。虽然它们都用于编码,但各自的用途和编码规则有所不同。本文将详细介绍这三个函数的区别。

基本介绍

  1. escape()(已废弃)

    • 最早的字符串编码函数
    • 已被废弃,不推荐使用
    • 将字符串转换为十六进制转义序列
  2. encodeURI()

    • 用于编码完整的 URI
    • 不会编码 URI 中的功能字符(如 :, /, ?, = 等)
    • 确保 URI 的完整性
  3. encodeURIComponent()

    • 用于编码 URI 的组成部分
    • 会编码所有特殊字符
    • 主要用于编码查询字符串参数

详细说明

escape()(已废弃)

javascript
escape("abc123"); // "abc123"
escape("äöü"); // "%E4%F6%FC"
escape("ć"); // "%u0107"
escape("@*_+-./"); // "@*_+-./"
  • 对于 ASCII 字母、数字和特定符号(@, *, _, +, -, ., /)不进行编码
  • 对于非 ASCII 字符,根据其 Unicode 值进行编码:
    • Unicode 值 < 256:使用 %xx 格式
    • Unicode 值 >= 256:使用 %uxxxx 格式
  • 由于已废弃,不应在新代码中使用

encodeURI()

javascript
const uri = "https://mozilla.org/?x=шеллы";
const encoded = encodeURI(uri);
console.log(encoded);
// "https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"
  • 用于编码完整的 URI
  • 不会编码以下字符:
    • ASCII 字母和数字
    • 保留字符:;, /, ?, :, @, &, =, +, $, ,
    • 非转义字符:-, _, ., !, ~, *, ', (, )
  • 会编码其他所有字符,包括非 ASCII 字符
  • 使用 UTF-8 编码方案

encodeURIComponent()

javascript
const param = "test?";
console.log(`?x=${encodeURIComponent(param)}`);
// "?x=test%3F"

const cyrillicParam = "шеллы";
console.log(`?x=${encodeURIComponent(cyrillicParam)}`);
// "?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"
  • 用于编码 URI 组件(如查询字符串参数)
  • 编码所有特殊字符,包括::, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, =
  • 只有以下字符不被编码:
    • ASCII 字母和数字
    • 非转义字符:-, _, ., !, ~, *, ', (, )
  • 同样使用 UTF-8 编码方案

区别对比

  1. 编码范围:

    • escape():最基础的编码,主要处理非 ASCII 字符
    • encodeURI():保留 URI 结构字符,适合编码完整 URI
    • encodeURIComponent():编码最全面,适合编码 URI 参数
  2. 编码方案:

    • escape():使用 Unicode 转义序列(%u)
    • encodeURI()encodeURIComponent():使用 UTF-8 编码
  3. 安全性:

    • escape():已废弃,不安全
    • encodeURI():安全,但不适合编码参数
    • encodeURIComponent():最安全,推荐用于参数编码

使用场景和最佳实践

  1. 完整 URL 编码:
javascript
const url = "https://example.com/path with spaces/";
const encodedUrl = encodeURI(url);
// https://example.com/path%20with%20spaces/
  1. 查询参数编码:
javascript
const baseUrl = "https://example.com/search";
const param = "query string & special chars";
const url = `${baseUrl}?q=${encodeURIComponent(param)}`;
// https://example.com/search?q=query%20string%20%26%20special%20chars
  1. 处理特殊字符:
javascript
const name = "Ben & Jerry's";
// 错误方式
const badUrl = encodeURI(`https://example.com/?choice=${name}`);
// 正确方式
const goodUrl = encodeURI(`https://example.com/?choice=${encodeURIComponent(name)}`);

最佳实践建议

  1. 永远不要使用 escape(),它已经被废弃。

  2. 使用 encodeURI() 当:

    • 需要编码完整的 URL
    • URL 中包含中文或其他非 ASCII 字符
    • 不想编码 URL 的功能字符(如 /, ?, = 等)
  3. 使用 encodeURIComponent() 当:

    • 编码 URL 参数
    • 编码包含特殊字符的字符串
    • 需要最严格的编码要求
  4. 处理查询参数时的推荐模式:

javascript
function buildUrl(baseUrl, params) {
  const url = new URL(baseUrl);
  Object.entries(params).forEach(([key, value]) => {
    url.searchParams.append(key, value);
  });
  return url.toString();
}

// 使用示例
const url = buildUrl("https://example.com", {
  name: "John & Jane",
  type: "search query"
});

通过正确使用这些编码函数,我们可以确保 URL 的安全性和正确性,避免因字符编码问题导致的错误。记住,在处理 URL 时,始终使用适当的编码函数,并注意它们之间的区别。

Released under the MIT License.