如何将 utf-16 表情符号代理对解码为 uf8-8 并在 html 中正确显示?

How to decode utf-16 emoji surrogate pairs into uf8-8 and display them correctly in html?

我有一个 字符串,其中包含 xml。它有以下 substring

<Subject>&amp;#55357;&amp;#56898;&amp;#55357;&amp;#56838;&amp;#55357;&amp;#56846;&amp;#55357;&amp;#56838;&amp;#55357;&amp;#56843;&amp;#55357;&amp;#56838;&amp;#55357;&amp;#56843;&amp;#55357;&amp;#56832;&amp;#55357;&amp;#56846;</subject>    

我正在从服务器中提取 xml,我需要将其显示给用户。我注意到 & 符号已被转义,并且有 utf-16 代理对。如何确保 emojis/emoticons 在浏览器中正确显示。

目前我只得到这些字符:��������������而不是实际的表情符号。

我正在寻找一种简单的方法来解决这个问题,如果可能的话,不需要任何外部库或任何第 3 方代码,只需简单的旧 javascript、html 或 css。

您可以使用 String.fromCharCode 将包含代理项的 UTF-16 代码单元转换为 JavaScript 字符串。下面的代码片段应该会给你一个想法。

var str = '&amp;#55357;&amp;#56898;ABC&amp;#55357;&amp;#56838;&amp;#55357;&amp;#56846;&amp;#55357;&amp;#56838;&amp;#55357;&amp;#56843;&amp;#55357;&amp;#56838;&amp;#55357;&amp;#56843;&amp;#55357;&amp;#56832;&amp;#55357;&amp;#56846;';

// Regex matching either a surrogate or a character.
var re = /&amp;#(\d+);|([^&])/g;
var match;
var charCodes = [];

// Find successive matches
while (match = re.exec(str)) {
  if (match[1] != null) {
    // Surrogate
    charCodes.push(match[1]);
  }
  else {
    // Unescaped character (assuming the code point is below 0x10000),
    charCodes.push(match[2].charCodeAt(0));
  }
}

// Create string from UTF-16 code units.
var result = String.fromCharCode.apply(null, charCodes);
console.log(result);