Javascript decodeURI(Component) malformed uri exception

105.2k views Asked by At

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.

2

There are 2 answers

5
Juicy Scripter On BEST ANSWER

%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')

3
Michael Nelles On

This may or may not apply to someone else's situation but this is what did it for me so I thought I would share. I upload and download lots of text files to a custom CMS.
the '%' sign in the source code was wreaking havoc for me.

// send to server
content = content.toString().replace(/%/g,'~~pct~~');       // ~~pct~~ <-made up replacement
content = encodeURI(content);

// get back from server / database
content = decodeURI(content);
content = content.toString().replace(/~~pct~~/g,'%');    // globally restore '%'