JavaScript中处理UTF-8编码与丹麦字符串的问题

3

我希望将一个长字符串转换为可下载的文件。其中包含丹麦字符,如果我尝试更改编码方式,则这些字符会被翻译成“�”或“�”。

以下是我的代码:

    function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf8,'+text);
  element.setAttribute('download', filename);
  element.style.display = 'none';
  document.body.appendChild(element);

  //element.click();

  document.body.removeChild(element);
}

function encode_utf8(s) {
  return unescape(encodeURIComponent(s));
}

function decode_utf8(s) {
  return decodeURIComponent(escape(s));
}

我尝试过对文本进行编码和解码,我还尝试了在字符集中使用 utf8、utf-8 和 iso-8859-1。但结果都相同。您有什么建议吗?

只要始终正确设置内容类型,就不应该需要使用这些 encode_utf8decode_utf8 函数。你有在任何地方调用它们吗? - Bergi
1个回答

0
您可以使用 String.fromCharCode() 而不是字符本身,例如: 230 相当于 æÆ 相当于 Æ,以此类推。
element.setAttribute('href', `http://www.Tr${String.fromCharCode(230)}kogslip.dk`);

我的使用情况涉及到设置fine-upload相关的文本

 document.querySelector(".qq-uploader-selector").setAttribute("qq-drop-area-text", `Tr${String.fromCharCode(230)}k og slip filer her`);

你可以使用这个网站 toptal 作为寻找 HTML 字符代码的参考。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接