Javascript string encoding Windows-1250 to UTF8

2020-05-03 11:59发布

问题:

I've an angularjs app that receive data from an external webservice.

I think I'm receiving UTF-8 string but encoded in ANSI.

For example I get

KLMÄšLENÃ    

When I want to display

KLMĚLENÍ

I've tried to use decodeURIComponent to convert it but that doesn't work.

var myString = "KLMÄšLENÃ"    
console.log(decodeURIComponent(myString))

I'm probably missing something but I can't find what.

Thanks and regards, Eric

回答1:

You can use TextDecoder. (Be beware! some browser does not support it.)

var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
  if (this.status == 200) {
    var dataView = new DataView(this.response);
    var decoder = new TextDecoder("utf-8");
    var decodedString = decoder.decode(dataView);
    console.log(decodedString);
  } else {
    console.error('Error while requesting', url, this);
  }
};
xhr.send();

Java servlet code for simulating server side output:

resp.setContentType("text/plain; charset=ISO-8859-1");
OutputStream os = resp.getOutputStream();
os.write("KLMĚLENÍ".getBytes("UTF-8"));
os.close();