In-browser JavaScript conversion GBK text to UTF8 encoding (Chrome, Firefox only)

Source: Internet
Author: User

When we use XMLHttpRequest to get the text content, if the server returned is GBK (or gb2312 and other non-UTF8 encoded) content, then get a bunch of garbled, how to convert to the default UTF8 encoded text in the browser?

In fact, if you are using Chrome or Firefox browser, it is very simple, you can use the browser built-in object Textdecoder to convert.

JavaScript Sample code:

if (' Textdecoder ' in window) {    var files = {      ' gbk.txt ': ' GBK '    };    Object.keys (Files). ForEach (function (file) {      fetchanddecode (file, Files[file]);}    );  } else {    Console.error (' Your browser does not support the Encoding API. ');  }  function Fetchanddecode (file, encoding) {    var xhr = new XMLHttpRequest ();    Xhr.open (' GET ', file);    Xhr.responsetype = ' Arraybuffer ';    Xhr.onload = function () {      if (this.status = =) {        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 ();  }
In fact, not just GBK, as long as the browser-supported encoding (see link 3), can be easily converted.
Reference:

1. Https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder

2. Easier ArrayBuffer String conversion with the Encoding API

3. https://encoding.spec.whatwg.org/

In-browser JavaScript conversion GBK text to UTF8 encoding (Chrome, Firefox only)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.