decodeURIComponent Rejects Malformed Escapes
decodeURIComponent throws URIError on bare percent signs, truncated escapes, and invalid hex, so decode user-controlled values inside a catching boundary.
Code
// 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');Output
Captured from a sandboxed run of this snippet in the build pipeline.
你好
a b+c
rejected "100%": true
rejected "%E4%BD": true
rejected "%ZZ": true
decoded utf-8: trueInside the snippet
One loop does the cycling here: for (const input of inputs).
The file’s state is a handful of top-level bindings: inputs, raw.
Caveats
- No third-party code is loaded at any point while this runs.
Using it
Running the file prints labeled results such as decoded:, rejected, decoded utf-8: — each operation’s effect is visible in the output.
Key statements
const inputs = ['100%', '%E4%BD', '%ZZ'];
const raw = 'sm%C3%B6rg%C3%A5sbord';
Interactive Tools for This Topic
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `inputs`, `raw`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.