How do I convert GBK to UTF8 with pure Javascript?

后端 未结 2 1586
闹比i
闹比i 2021-01-16 19:07

I want to load some text from other site wich the content is GBK encoded, but my site is UTF8.

Is there anyway by which I can convert these GBK text into UTF8 for di

2条回答
  •  Happy的楠姐
    2021-01-16 19:53

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

    For chrome or firefox, you could use TextDecoder to decode any text to 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'); 
    

提交回复
热议问题