← 中文资源

简体中文版本

decodeURIComponent 拒绝畸形转义序列

decodeURIComponent 对裸 %、截断转义与非法十六进制抛 URIError:用户可控的转义文本要在自己的边界里解码并捕获。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

你好
a b+c
rejected "100%": true
rejected "%E4%BD": true
rejected "%ZZ": true
decoded utf-8: true

实现说明

在这里做循环的是 for (const input of inputs)。 各个操作都建立在顶层绑定之上:inputs、raw。

使用要点

  • 每一步打印都带着自己的标签:rejected、decoded utf-8:。

常见问题

包管理器会看到什么?

一份空的依赖清单。示例没有需要抓取的导入。 文件的状态由几个模块级绑定持有:inputs、raw。

核心语句

const inputs = ['100%', '%E4%BD', '%ZZ'];
const raw = 'sm%C3%B6rg%C3%A5sbord';

代码示例

// Well-formed percent escapes decode cleanly
console.log(decodeURIComponent('%E4%BD%A0%E5%A5%BD'));
console.log(decodeURIComponent('a%20b%2Bc'));

// A bare %, a truncated escape, or invalid hex all throw URIError
const inputs = ['100%', '%E4%BD', '%ZZ'];
for (const input of inputs) {
  try {
    console.log('decoded:', decodeURIComponent(input));
  } catch (err) {
    console.log('rejected ' + JSON.stringify(input) + ':', err instanceof URIError);
  }
}

// Decode at your own boundary: user-controlled text with one malformed escape
// surfaces as a handled URIError instead of escaping to callers
const raw = 'sm%C3%B6rg%C3%A5sbord';
console.log('decoded utf-8:', decodeURIComponent(raw) === 'smörgåsbord');