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);
The decodeURI() function expects a valid URI as its parameter. If you are only trying to decode a string instead of a full URI, use decodeURIComponent()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.