Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does unescape work but decodeURI doesn't?

Tags:

javascript

I have the following variable:

var string="Mazatl%E1n";

The string is returned like that by the server. All I want to do is decode that into: Mazatlán. I've tried the following:

var string="Mazatl%E1n";

alert(unescape(string));
alert(decodeURI(string));

unescape works fine but I don't want to use it because I understand it is deprecated, instead I tried decodeURI wich fails with the following error:

Uncaught URIError: URI malformed

Why ? Any help is appreciated.

var string="Mazatl%E1n";

alert(unescape(string));
alert(decodeURI(string));
like image 770
angelcool.net Avatar asked Jan 12 '16 22:01

angelcool.net


Video Answer


2 Answers

You get the error because %E1 is the Unicode encoding, but decodeURI() expects UTF-8.

You'll either have to create your own unescape function, for example:

function unicodeUnEscape(string) {
  return string.replace(/%u([\dA-Z]{4})|%([\dA-Z]{2})/g, function(_, m1, m2) {
    return String.fromCharCode(parseInt("0x" + (m1 || m2)));
  })
}

var string = "Mazatl%E1n";
document.body.innerHTML = unicodeUnEscape(string);

or you could change the server to send the string encoded in UTF-8 instead, in which case you can use decodeURI()

var string = "Mazatl%C3%A1n"
document.body.innerHTML = decodeURI(string);
like image 125
Johan Karlsson Avatar answered Oct 11 '22 00:10

Johan Karlsson


URI supports the ASCII character-set , and the correct format encoding for á is %C3%A1 (in UTF-8 encoding)

fiddle


escape and unescape use an hexadecimal escape sequences
(which is different ..);
so the value you're getting form the server has been encoded using escape(string).

like image 39
maioman Avatar answered Oct 11 '22 00:10

maioman