编码Windows-1250到UTF8的Javascript字符串



我有一个从外部webservice接收数据的angularjs应用。

我认为我正在接收UTF-8字符串,但在ANSI中编码。

例如我得到

KLMÄšLENÃ    

当我想显示

KLMĚLENÍ

我已经尝试使用decodeuriccomponent来转换它,但那不起作用。

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

我可能错过了什么,但我找不到。

谢谢Eric

您可以使用TextDecoder。(小心!有些浏览器不支持

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代码:

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

只是原始答案的现代化版本:

await fetch(url)
    .then(res => res.arrayBuffer())
    .then(buff => new TextDecoder('windows-1250').decode(buff));