JS 禁止 input 輸入 emoji 的方法

在專案開發裡,表單是很常見的東西,要是規格上禁止輸入 emoji 符號該怎麼辦呢?emoji 是怎麼來的?這就要從 Unicode 編碼說起

Unicode

The Unicode codepoint range goes from U+0000 to U+10FFFF which is over 1 million symbols, and these are divided into groups called planes. Each plane is about 65000 characters (16^4). The first plane is the Basic Multilingual Plane (U+0000 through U+FFFF) and contains all the common symbols we use everyday and then some. The rest of the planes require more than 4 hexadecimal digits and are called supplementary planes or astral planes.

也就是說 Unicode 的編碼範圍是 U+000 到 U+10FFFF,能對應到 100 多萬個符號 (0x10FFF === 1114111)。

方法

如何解決呢?就是用正規表達式!

const emoji = /[\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/gi;
      
el.value.replace(emoji, "");

如果是用 Vue 就可以用 directive 方式做:

import Vue from "vue";

// input 禁止有 emoji 表情
export const cantEmoji = Vue.directive("cantEmoji", {
  bind: function(el) {
    el.handler = function() {
      // 判断是否含有 emoji 表情
      const emoji = /[\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/gi;
      el.value = el.value.replace(emoji, "");
    };
    el.addEventListener("input", el.handler);
  },
  unbind: function(el) {
    el.removeEventListener("input", el.handler);
  }
});

參考資料

https://www.itread01.com/qhkhke.html
https://cloud.tencent.com/developer/article/1444649

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *