Vue

by wukong

HTML

<div id="app">
  <div>
    <p>原始表情:{{ emoji }}</p>
    <p>JSON编码(stringify):{{ emoji2 }}</p>
    <p>编码之后还原(parse):{{ emoji3 }}</p>
    <p>转换为Unicode编码(parseUnicode):{{ emoji4 }}</p>
    <p>转换为实体字符(utf16toEntities):{{ emoji5 }}</p>
    <p>v-html:</p>
    <p v-html="emoji5"></p>
  </div>
</div>

Vue

new Vue({
  el: "#app",
  data: {
    emoji:'',
    emoji1:'',
    emoji2:'',
    emoji3:'',
    emoji4:'',
   	emoji5:'',
  },
  
  mounted() {
    this.emoji = "表情😀";
    let emojiToUnicode = this.emojiToUnicode(this.emoji);
    this.emoji2 = JSON.stringify(emojiToUnicode);
    this.emoji3 = JSON.parse(this.emoji2);
    this.emoji4 = this.parseUnicode(this.emoji);
    //实体字符
    this.emoji5 = this.utf16toEntities(this.emoji);
  },
  
  methods: {
  	emojiToUnicode(emoji) {
    let backStr = "";
    if (emoji && emoji.length > 0) {
      for (const char of emoji) {
        const index = char.codePointAt(0);
        if (index > 65535) {
          const h =
            "\\u" +
            (Math.floor((index - 0x10000) / 0x400) + 0xd800).toString(16);
          const c = "\\u" + (((index - 0x10000) % 0x400) + 0xdc00).toString(16);
          backStr = backStr + h + c;
        } else {
          backStr = backStr + char;
        }
      }
      console.log(backStr);
    }
    return backStr;
  },
  //  https://stackoverflow.com/questions/33685680/emoji-surrogate-string-with-javascript-how-to-parse
  parseUnicode(str) {
    const r = /\\u([\d\w]{4})/gi;
    str = str.replace(r, function(match, grp) {
      return String.fromCharCode(parseInt(grp, 16));
    });
    return str;
  },
  utf16toEntities(str) {
    const patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
    str = str.replace(patt, function(char) {
      let 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;
  }
  }
})