isWellFormed Guards Strings Before UTF-8

Detect lone UTF-16 surrogates with String.prototype.isWellFormed before calling encodeURIComponent, using toWellFormed only when lossy repair fits.

JavascriptSecurity Boundaries

Code

snippet
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()));
    }
  }
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Stepwise trace — isWellFormed Guards Strings Before UTF-8

The loop for (const text of inputs) is the only repeated construct.

Everything operates on top-level bindings: inputs.

Points of care

  • The package manager never enters the picture for this snippet.

Putting it to use

The file’s steps show up in the output as ok :, rejected:.

Core lines

encodeURIComponent(text);

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. Its state lives in module-level bindings: `inputs`.