js解决emoji不展示以及存储问题。

参考:https://www.bianchengquan.com/article/144145.html

     https://zhuanlan.zhihu.com/p/41926228

   https://juejin.cn/post/6844903637555101704

 

  1.展示效果:

      🈶保单📃,🈶车🚗,🈶房🏠
      🈶工资💳,🈶烟草🌿,🈶税票

   1️⃣👩‍❤️‍💋‍👩

  2.unicode编码  

[<U+1f236>]保单[<U+1f4c3>],[<U+1f236>]车[<U+1f697>],[<U+1f236>]房[<U+1f3e0>]
[<U+1f236>]工资[<U+1f4b3>],[<U+1f236>]烟草[<U+1f33f>],[<U+1f236>]税票
[<U+0031-fe0f-20e3>][<U+1f469-200d-2764-fe0f-200d-1f48b-200d-1f469>] // 这种是组合emoji

      3.unicode编码转换成emoji表情展示

    fromCodePointMehod (codes) {
      if (!String.fromCodePoint) { // String.fromCodePoint方法是有兼容性问题
          String.fromCodePoint = function fromCodePoint () {
            var chars = [], point, offset, units, i;
            for (i = 0; i < arguments.length; ++i) {
              point = arguments[i];
              offset = point - 0x10000;
              units = point > 0xFFFF ? [0xD800 + (offset >> 10), 0xDC00 + (offset & 0x3FF)] : [point];
              chars.push(String.fromCharCode.apply(null, units));
            }
            return chars.join("");
          }
        } 
        return String.fromCodePoint.apply(null, codes);
    },
    unicodeChange(str) {
      const emojiDecodeRegex = /\[\<U+(.*?)\>\]/g;
      return str.replace(emojiDecodeRegex, p => {
        const filterP = p.replace(/\[\<U\+|>]/g, '');
        var codes = filterP.split('-').map(function(value, index) {
            return parseInt(value, 16);
        });
        return this.fromCodePointMehod(codes)
      });
    }, 

  4.存储和回显转换

    encodeEmoji(str) {
      const emojiRegex = require('emoji-regex');
      const regex = emojiRegex();
      return str.replace(regex, p => {
        let arr = []
        for (let ch of p) {
          arr.push(ch.codePointAt(0))
        }
        return `emoji(${arr.join('-')})`  // 组合emoji用-拼接传递
      });
    },
    deCodeEmoji(str) {
      const emojiDecodeRegex = /emoji\((.*?)\)/g;
      return str.replace(emojiDecodeRegex, p => {
        const filterP = p.replace(/emoji\(|\)/g, '');
        var codes = filterP.split('-').map(function(value, index) {
            return parseInt(value);
        });
        return this.fromCodePointMehod(codes)
      });
    },

 

posted @ 2022-05-05 11:23  勤勤恳恳小码农  阅读(309)  评论(0)    收藏  举报