入库之前操作(数据库编码不用更改 本人用mysql):
var patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
content = content.replace(patt, function (char) {
var H, L, code;
if (char.length === 2) {
H = char.charCodeAt(0); // 取出高位
L = char.charCodeAt(1); // 取出低位
code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法
return "&#" + code + ";";
} else {
return char;
}
});
前台展示处理(h5不用加此段代码)###
//表情转换显示
function entitiesToUtf16(str) {
return str.replace(/&#(\d+);/g, function (match, dec) {
let H = Math.floor((dec - 0x10000) / 0x400) + 0xD800;
let L = Math.floor(dec - 0x10000) % 0x400 + 0xDC00;
return String.fromCharCode(H, L);
});
}