Convert gbk text to UTF8 encoding using javascript in the browser (chrome, firefox only)

Source: Internet
Author: User

Convert gbk text to UTF8 encoding using javascript in the browser (chrome, firefox only)

When we use xmlhttprequest to retrieve text content, if the server returns gbk (or gb2312 or other non-utf8 encoded content), a bunch of garbled characters are obtained, how do I convert to the default UTF-8 encoded text in the browser?

In fact, if you are using the chrome or firefox browser, it is very simple. You can use the built-in browser object TextDecoder for conversion.

Javascript sample code:

 

if ('TextDecoder' in window) {    var files = {      'gbk.txt': 'gbk'    };    Object.keys(files).forEach(function(file) {      fetchAndDecode(file, files[file]);    });www.bkjia.com  } 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 == 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();  }
In fact, not only gbk, as long as the encoding supported by the browser (see link 3), can be easily converted.
 

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.