【问题标题】:How do I convert GBK to UTF8 with pure JavaScript?如何使用纯 JavaScript 将 GBK 转换为 UTF8?
【发布时间】:2013-06-20 10:52:32
【问题描述】:

我想从其他网站加载一些内容为 GBK 编码的文本,但我的网站是 UTF8。

有什么方法可以将这些GBK文本转换成UTF8显示?

由于某些原因,我只能为此使用 JavaScript。

【问题讨论】:

    标签: javascript encoding utf-8 gbk


    【解决方案1】:

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

    有一个javascript可以在gbk和unicode之间进行转换:which maps all the 21886 gbk Chinese chars to unicode

    您可以简单地下载 javascript file ,包含它并使用:

    unicode to gbk:

    $URL.encode(unicode_string)

    或 gbk 转 unicode:

    $URL.decode(gbk_string)

    我测试过了。它在我的网站上运行良好:zhuhaiyang.sinaapp.com/base64/index.html

    使用纯 javascript 执行 base64 。

    【讨论】:

    【解决方案2】:

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

    对于 chrome 或 firefox,您可以使用 TextDecoder 将任何文本解码为 un​​icode:

    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'); 
    

    【讨论】:

      猜你喜欢
      • 2022-12-16
      • 2020-07-24
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      相关资源
      最近更新 更多