java string.getBytes(“UTF-8”) javascript equivalent
2022-09-04 07:22:09
我在java中有这个字符串:
"test.message"
byte[] bytes = plaintext.getBytes("UTF-8");
//result: [116, 101, 115, 116, 46, 109, 101, 115, 115, 97, 103, 101]
如果我在javascript中做同样的事情:
stringToByteArray: function (str) {
str = unescape(encodeURIComponent(str));
var bytes = new Array(str.length);
for (var i = 0; i < str.length; ++i)
bytes[i] = str.charCodeAt(i);
return bytes;
},
我得到:
[7,163,140,72,178,72,244,241,149,43,67,124]
我的印象是 unescape(encodeURIComponent()) 会正确地将字符串转换为 UTF-8。难道不是这样吗?
参考:
http://ecmanaut.blogspot.be/2006/07/encoding-decoding-utf8-in-javascript.html