← 中文资源

简体中文版本

isWellFormed 在编码前拦截孤立代理项

在调用 encodeURIComponent 前先用 String.prototype.isWellFormed 检查字符串,提前拦下会导致 URIError 的孤立代理项,再按需决定拒绝或修复。

阅读英文原文

运行结果

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

ok     : valid-emoji-%F0%9F%9A%80
rejected: URIError -> repaired: broken-high-%EF%BF%BD-tail
rejected: URIError -> repaired: broken-low-%EF%BF%BD-head

实现说明

这个文件只在 for (const text of inputs) 里循环。 各个操作都建立在顶层绑定之上:inputs。

使用要点

  • 它调用的每样东西都是语言核心文档化的组成部分。
  • 直接运行文件,输出会带上标签,比如 ok :、rejected:——输出的每一行都能指回产生它的那次调用。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件用顶层绑定保存自己的状态:inputs。

核心语句

encodeURIComponent(text);

代码示例

const inputs = [
  'valid-emoji-' + String.fromCodePoint(0x1f680),
  'broken-high-' + String.fromCharCode(0xd800) + '-tail',
  'broken-low-' + String.fromCharCode(0xdc00) + '-head',
];

for (const text of inputs) {
  if (text.isWellFormed()) {
    console.log('ok     :', encodeURIComponent(text));
  } else {
    // Lone surrogates make encodeURIComponent throw URIError; repair only when permitted
    try {
      encodeURIComponent(text);
    } catch (err) {
      console.log('rejected:', err.name, '-> repaired:', encodeURIComponent(text.toWellFormed()));
    }
  }
}