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));
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);
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With