简体   繁体   中英

Convert character to correct ASCII-extended integer value in Javascript

Code below contains a JS function that receives as parameter String "€€" (Euro sign). I need to convert each one of these characters to its ASCII-extended integer equivalent (128 with ISO-8859-1).

However, t[0] and t[1] take value "8364" instead of "128". What am I doing wrong? Please note that if I use UTF-8 instead of ISO-8859-1, they take value 65533 and in the JS debugger (Chrome and IE developer tools) a question mark is displayed instead of € symbol.

Thanks a mil

<html>
<head>
<meta http-equiv="Content-Type" content="text/javascript; charset=ISO-8859-1">
<title>JavaScript Scripting</title>
</head>
<body>
<script type="text/javascript" charset="ISO-8859-1">
function d(s) 
{
    var data = (s + "").split("");
    var dataLength = data.length;
    var t = [dataLength],n;

    for(n=0;n<dataLength;n++)
    t[n]=data[n].charCodeAt(0);
}
d("€€");
</script>
</body>
</html>

Full story is that I pasted this "€€" from file "output.js", where these two bytes were written by Java code below, representing integers [128,128]. That is why I need t[0] and t[1] to get value 128.

res.setContentType("application/octet-stream"); 
res.setHeader("Content-Disposition","attachment;filename=output.js;charset=ISO-8859-1");
ServletOutputStream os = res.getOutputStream();
char result[]=encode(req.getParameter("originalScript"));
// result[0] and result[1] have here integer value 128
String result2=new String(result);
// result2 is displayed here as non printable characters (blank)
os.print(result2);
// On output.js "€€" is displayed

You have to make sure that the file is actually saved as ISO-8859-1, but that is actually not possible as there is no € character in that character set.

"ISO/IEC 8859-1 is missing [...] the euro sign."

http://en.wikipedia.org/wiki/ISO/IEC_8859-1

As you are getting the character code 8364, the file is most likely saved as UTF-8, as that character code corresponds with the unicode character € .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM