java string.getBytes("UTF-8")javascript等价物

Wes*_*ley 8 javascript java byte utf-8 utf-16

我在java中有这个字符串:

"test.message"

byte[] bytes = plaintext.getBytes("UTF-8");
//result: [116, 101, 115, 116, 46, 109, 101, 115, 115, 97, 103, 101]
Run Code Online (Sandbox Code Playgroud)

如果我在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;
    },
Run Code Online (Sandbox Code Playgroud)

我明白了:

 [7,163,140,72,178,72,244,241,149,43,67,124]
Run Code Online (Sandbox Code Playgroud)

我的印象是unescape(encodeURIComponent())会正确地将字符串转换为UTF-8.这不是这种情况吗?

参考:

http://ecmanaut.blogspot.be/2006/07/encoding-decoding-utf8-in-javascript.html

Kev*_*son 9

您可以使用TextEncoder哪个是编码生活标准的一部分.根据Chromium Dashboard 的Encoding API条目,它在Firefox中提供,将在Chrome 38中提供.还有一个文本编码的 polyfill可用.

下面的JavaScript代码示例返回一个Uint8Array填充了您期望的值.

var s = "test.message";
var encoder = new TextEncoder();
encoder.encode(s);
// [116, 101, 115, 116, 46, 109, 101, 115, 115, 97, 103, 101]
Run Code Online (Sandbox Code Playgroud)


Pau*_* S. 8

JavaScript没有String的字符编码概念,一切都是UTF-16.大多数的时间时间的价值charUTF-16相匹配UTF-8 ,这样你就可以忘记它的任何不同.

还有更好的方法可以做到这一点

function s(x) {return x.charCodeAt(0);}
"test.message".split('').map(s);
// [116, 101, 115, 116, 46, 109, 101, 115, 115, 97, 103, 101]
Run Code Online (Sandbox Code Playgroud)

那是unescape(encodeURIComponent(str))做什么的?让我们分别看一下,

  1. encodeURIComponentURI语法中str非法或具有意义的每个字符转换为URI转义版本,以便将其用作URI的搜索组件中的键或值时没有问题,例如请注意这是如何现在的6字符长字符串.encodeURIComponent('&='); // "%26%3D"
  2. unescape实际上是折旧的,但它的工作类似于(decodeURIdecodeURIComponent相反encodeURIComponent).如果我们查看ES5规范,我们可以看到11. Let c be the character whose code unit value is the integer represented by the four hexadecimal digits at positions k+2, k+3, k+4, and k+5 within Result(1).
    ,4数字是2字节是"UTF-8",但正如我所提到的,所有字符串都是UTF-16,所以它实际上是一个UTF-16字符串,将自己限制为UTF-8.