🚀
头像

默永


人生就像骑单车,想保持平衡就得往前走。

js转换emoji表情,变相解决数据库不能存表情

2021-11-29 18:05:54 276 💗 1 @默永

转义成字符串

var str = "表情😀123456" 
function utf16toEntities(str) { 
var patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
        str = str.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;
            }
    });
    return str;
} 
var str01 = utf16toEntities(str) 
console.log(str01) //表情😀123456

转译成表情

//将字符串转换成表情
uncodeUtf16(str) {
    var reg = /\&#.*?;/g;
    var result = str.replace(reg, function (char) {
        var H, L, code;
        if (char.length == 9) {
            code = parseInt(char.match(/[0-9]+/g));
            H = Math.floor((code - 0x10000) / 0x400) + 0xD800;
            L = (code - 0x10000) % 0x400 + 0xDC00;
            return unescape("%u" + H.toString(16) + "%u" + L.toString(16));
        } else {
            return char;
        }
    });
    return result;
}
var str02 = utf16toEntities('😀123456') 
console.log(str02) //表情😀123456

使用正则过滤emoji表情

const regStr = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/g;

if (regStr.test(text)) {
    content = text.replace(regStr, '');
}
    目录导航