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.
Code
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-headStepwise 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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Its state lives in module-level bindings: `inputs`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.