Javascript decodeURI(Component) malformed uri exception

Christian picture Christian · Jan 30, 2012 · Viewed 70.3k times · Source

I entered the following in Chrome's console:

decodeURIComponent('a%AFc');

Instead of resulting to a0xAFc, it caused a URIError exception (malformed uri).

I've heard several excuses why this may be possible, but what I don't understand is why?

The decodeURIComponent() function in particular is supposed to decode data, not verify the URI.

Answer

Juicy Scripter picture Juicy Scripter · Jan 30, 2012

%AF is not a character on his own but part of Unicode sequence (MACRON - %C2%AF).

%AF wasn't produced by encodeURIComponent but something like escape, so it can be decoded by unescape.

What you probably need is decodeURIComponent('%C2%AF')