我有一个包含xml的字符串。它具有以下子字符串
<Subject>&#55357;&#56898;&#55357;&#56838;&#55357;&#56846;&#55357;&#56838;&#55357;&#56843;&#55357;&#56838;&#55357;&#56843;&#55357;&#56832;&#55357;&#56846;</subject>
我正在从服务器中提取xml,我需要将其显示给用户。我注意到 & 符号已被转义,并且有 utf-16 代理项对。如何确保表情符号/表情符号在浏览器中正确显示。
目前我只是得到这些字符:而不是实际的表情符号。
我正在寻找一种简单的方法来解决此问题,而无需任何外部库或任何第三方代码(如果可能的话,只需普通的旧JavaScript,html或css(。
您可以将包括代理项在内的 UTF-16 代码单元转换为带有String.fromCharCode
的 JavaScript 字符串。下面的代码片段应该给你一个想法。
var str = '&#55357;&#56898;ABC&#55357;&#56838;&#55357;&#56846;&#55357;&#56838;&#55357;&#56843;&#55357;&#56838;&#55357;&#56843;&#55357;&#56832;&#55357;&#56846;';
// Regex matching either a surrogate or a character.
var re = /&#(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);