简体   繁体   English

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

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

I have a string which contains xml . 我有一个包含xml字符串 It has the following 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>    

I'm pulling the xml from a server and I need to display it to the user. 我正在从服务器中提取xml ,我需要将其显示给用户。 I've noticed the ampersand has been escaped and there are utf-16 surrogate pairs. 我注意到“&”号已被转义,并且有utf-16代理对。 How do I ensure the emojis/emoticons are displayed correctly in a browser. 如何确保表情符号/表情符号在浏览器中正确显示。

Currently I'm just getting these characters: instead of the actual emojis. 目前我只得到以下字符: 而不是实际的表情符号。

I'm looking for a simple way to fix this without any external libraries or any 3rd party code if possible just plain old javascript, html or css. 我正在寻找一种简单的方法来解决此问题,而无需任何外部库或任何第三方代码(如果可能的话)只是普通的旧javascript,html或css。

You can convert UTF-16 code units including surrogates to a JavaScript string with String.fromCharCode . 您可以使用String.fromCharCode将包括代理在内的UTF-16代码单元转换为JavaScript字符串。 The following code snippet should give you an idea. 以下代码段应为您提供一个思路。

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM