2013-06-20 35 views
0

我想從其他網站加載一些文本,內容是GBK編碼的,但我的網站是UTF8。如何用純Javascript將GBK轉換爲UTF8?

無論如何,我可以將這些GBK文本轉換爲UTF8進行顯示嗎?

由於某些原因,我只能對此使用Javascript。

回答

1

http://www.1kjs.com/lib/widget/gbk/

還有就是GBK和Unicode之間轉換的javascript:which maps all the 21886 gbk Chinese chars to unicode

您可以只需下載javascript file,包括它使用:

統一爲GBK:

$URL.encode(unicode_string)

或GBK爲Unicode:

$URL.decode(gbk_string)

我測試。它在我的網站上運行良好:zhuhaiyang.sinaapp.com/base64/index.html

它使用純JavaScript來執行base64 ency。

+1

鏈接http://www.1kjs.com/lib/widget/gbk/沒有按不再工作了。你知道另一個位置嗎? – ErikR

0

http://updates.html5rocks.com/2014/08/Easier-ArrayBuffer---String-conversion-with-the-Encoding-API

對於Chrome或Firefox,你可以使用TextDecoder到任何文本爲Unicode解碼:

function fetchAndDecode(file, encoding) { 
    var xhr = new XMLHttpRequest(); 
    xhr.open('GET', file); 
    xhr.responseType = 'arraybuffer'; 
    xhr.onload = function() { 
     if (this.status == 200) { 
     var dataView = new DataView(this.response); 
     var decoder = new TextDecoder(encoding); 
     var decodedString = decoder.decode(dataView); 
     console.info(decodedString); 
     } else { 
     console.error('Error while requesting', file, this); 
     } 
    }; 
    xhr.send(); 
    } 

fetchAndDecode('gbkencoded.txt','gbk');