← 返回完整题库
JavaScript中等

为什么有时要用 encodeURIComponent 而不只是 encodeURI?

参考答案

encodeURI 会保留 URL 的结构字符(& = ? / : # + , 等),适合编码整条地址;但它不会编码 &、=、?,所以放在参数值里会破坏 query 结构:

const q = 'a=1&b=2';
'https://x.com/?q=' + encodeURI(q);            // q 中的 & 未编码 → 被解析成两个参数(错)
'https://x.com/?q=' + encodeURIComponent(q);   // & → %26,参数完整(对)

规则

  • 整条 URL:encodeURI;
  • 参数值 / 路径片段:encodeURIComponent(额外编码 :/?#[]@&+=$,);
  • 解码对应 decodeURI / decodeURIComponent。

注意:encodeURIComponent 不编码 !'()*-._~,服务端需按同一规则解码;不要对已编码字符串重复编码。

本题来自 计算机知识面试题库,共 921 道题。