2014-04-04 28 views
3

我有這個字符串在java中:的Java string.getBytes( 「UTF-8」)的JavaScript相當於

"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

回答

5

的JavaScript字符串無字符編碼的概念,一切都在UTF-16。大多數時間的值爲char in UTF-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] 

那麼,什麼是unescape(encodeURIComponent(str))在做什麼?讓我們來看看每個單獨,

  1. encodeURIComponent正在轉換的每個字符在str這是非法的或有URI語法意義爲URI轉義版本,以便有使用它作爲一個關鍵的還是沒有問題URI的搜索組件中的值,例如encodeURIComponent('&='); // "%26%3D"請注意,現在這是一個6字符長的字符串字符串
  2. unescape實際上是折舊的,但它的工作類似於decodeURIdecodeURIComponent(與encodeURIComponent相反)。如果我們在ES5 spec看,我們可以看到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
+0

我不能忘記它有什麼不同,因爲我需要支持中文。 – Wesley

+0

順便說一句,如果你讀這個,他們建議unescape(encodeUricomponent())從utf16獲取utf8值:http://ecmanaut.blogspot.be/2006/07/encoding-decoding-utf8-in-javascript.html – Wesley

+0

所以,是有解決方案嗎? – Wesley

5

您可以使用TextEncoder,它是Encoding Living Standard的一部分。根據Chromium Dashboard上的Encoding API條目,它在Firefox中發貨,並將在Chrome 38中發佈。還有一個text-encoding可用填充。

下面的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]