简体   繁体   中英

Javascript string encoding Windows-1250 to UTF8

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM