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



我有一个包含xml字符串。它具有以下子字符串

<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 代理项对。如何确保表情符号/表情符号在浏览器中正确显示。

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

我正在寻找一种简单的方法来解决此问题,而无需任何外部库或任何第三方代码(如果可能的话,只需普通的旧JavaScript,html或css(。

您可以将包括代理项在内的 UTF-16 代码单元转换为带有String.fromCharCode的 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);

最新更新