JavaScript encodeURI 与 encodeURIComponent 的区别

encodeURI() 保留 URL 中的结构分隔符。encodeURIComponent() 适合编码搜索词等单个值。构造查询时可以把原始值传给 URLSearchParams。在相应层级解码,并处理无效的百分号序列。

四个函数各自处理什么

URI(统一资源标识符)用于标识资源,URL 表示资源位置。百分号编码用 %HH 表示字节,非 ASCII 字符可能对应多个 UTF-8 字节。它不加密数据。encodeURIComponent() 保留字母、数字和 - _ . ! ~ * ' ( ) 等字符,但比 encodeURI() 编码更多分隔符。

函数 用途 分隔符处理
encodeURI() 完整 URI 保留结构分隔符,例如 :, /, ?, &, =, #
encodeURIComponent() 路径段或查询值 将分隔符作为数据编码
decodeURI() 解码完整 URI 保留部分已编码的保留分隔符
decodeURIComponent() 解码单个值 解码百分号序列,包括分隔符
encodeURI("a&b=c");          // "a&b=c"
encodeURIComponent("a&b=c"); // "a%26b%3Dc"

decodeURI("%26");          // "%26"
decodeURIComponent("%26"); // "&"

构建搜索 URL 的完整示例

把完整代码以 UTF-8 保存为 url-encoding.html 后打开。它构造 URL 并读回值,不发送请求。s 是搜索参数。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Encode and decode URL values</title>
</head>
<body>
<h1>Put a search term in a URL</h1>
<label for="keyword">Search term</label>
<input id="keyword" value="C++ &amp; Café">
<button id="encode" type="button">Encode</button>
<button id="restore" type="button">Restore defaults</button>
<pre id="output"></pre>
<label for="encoded">Encoded value</label>
<input id="encoded" value="Caf%C3%A9">
<button id="decode" type="button">Decode</button>
<pre id="decoded"></pre>
<script>
const keyword = document.getElementById("keyword");
const output = document.getElementById("output");
function encode() {
  try {
    const value = keyword.value;
    const component = encodeURIComponent(value);
    const url = new URL("https://www.codingfactory.net/");
    url.searchParams.set("s", value);
    output.textContent = [
      `encodeURI: ${encodeURI(value)}`,
      `encodeURIComponent: ${component}`,
      `Decoded again: ${decodeURIComponent(component)}`,
      `Search URL: ${url.href}`,
      `Value from URL: ${url.searchParams.get("s")}`
    ].join("\n");
  } catch (error) {
    output.textContent = error.name;
  }
}
document.getElementById("encode").addEventListener("click", encode);
document.getElementById("restore").addEventListener("click", () => {
  keyword.value = "C++ & Café";
  encode();
});
document.getElementById("decode").addEventListener("click", () => {
  try {
    document.getElementById("decoded").textContent =
      decodeURIComponent(document.getElementById("encoded").value);
  } catch (error) {
    document.getElementById("decoded").textContent = error.name;
  }
});
encode();
</script>
</body>
</html>

encodeURI() 保留 + 和 &,encodeURIComponent() 将其转换为 %2B 和 %26。?s= 后的裸 & 可能开始另一个参数。URLSearchParams 把空格序列化为 +,把实际加号写成 %2B。检查读回的 C++ & Café,尝试 a&b=1 后还原。给 set() 传原始字符串。

区分解码失败与重复编码

初始解码结果为 Café。改成 % 或 %E0%A4%A 会显示 URIError。孤立的 UTF-16 代理码元也可能导致编码失败。示例只显示错误名称。参见 URIError。

const once = encodeURIComponent("&"); // "%26"
const twice = encodeURIComponent(once); // "%2526"

decodeURIComponent(twice); // "%26": decodes one layer only
decodeURIComponent("a+b"); // "a+b": does not turn a plus into a space

每层只解码一次。URLSearchParams.get() 返回已解码的值,再解码可能改变原始数据。decodeURIComponent() 保留普通加号,解析查询时则会把加号当成空格。

单独检查 URL 目标

编码不会检查目标地址。若外部输入可决定跳转地址,应单独检查协议与主机。用 textContent 以文字显示数据。

同时构建路径段和查询值

在 Console 执行代码。只编码商品名,让斜杠仍属于同一个路径段。将原始类别传给 searchParams.set()。代码不会发出网络请求。

{
  const item = "Part A/B";
  const category = "Café + tea";
  const url = new URL("https://example.com/");
  url.pathname = "/items/" + encodeURIComponent(item);
  url.searchParams.set("category", category);

  console.log(url.href);
  console.log(decodeURIComponent(url.pathname.split("/").at(-1)));
  console.log(url.searchParams.get("category"));
}

首行是 https://example.com/items/Part%20A%2FB?category=Caf%C3%A9+%2B+tea,接下来是 Part A/B 和 Café + tea。先分割路径,再对目标段解码。URL 解析会规范化 . 和 ..。如果服务器以不同方式处理编码后的斜杠,可以通过查询参数传递标识符。