将表情符号代码点转换为JavaScript

时间:2018-03-27 03:34:24

标签: javascript github github-api emoji

我正在尝试从the GitHub API加载表情符号,并将代码点转换为JavaScript中的字符串。这适用于由单个代码点组成的表情符号,但对于由多个点组成的表情符号无效,例如family_woman_woman_girl_girl。我正在使用zero width joiner (zwj)来连接字符。

const list = document.getElementById('emojis');
const zwj = '\u200D';

async function renderList() {
  // load the github emojis: https://developer.github.com/v3/emojis/
  const response = await fetch('https://api.github.com/emojis');
  const data = await response.json();
  
  // render a list item for each emoji
  for (const [key, value] of Object.entries(data)) {
    // skip GitHub's custom emoji
    if (!/\/unicode\//.test(value)) {
      continue;
    }
    
    // parse the url into an array of code points
    const codePoints = value
      .substr(57)
      .replace(/\.png\?.*$/, '')
      .split('-')
      .map(hex => parseInt(hex, 16));
    
    // translate the code points to a string. SOMETHING WRONG HERE
    const emoji = codePoints
      .map(p => String.fromCodePoint(p))
      .join(zwj);
    
    // render the list item
    const li = document.createElement('li');
    li.textContent = `${key}: ${codePoints} ${emoji}`;
    list.appendChild(li);
  }
}

renderList();
<ul id="emojis"></ul>

1 个答案:

答案 0 :(得分:0)

并非所有的表情符号序列都与ZWJ粘在一起。最值得注意的是,人们和他们的肤色简单地结合在一起,没有任何填充物。

Unicode维护a list of all code points/combinations它认为是表情符号。 emoji-data.txt文件都是single-cp表情符号。 emoji-zwj-sequences.txt所有序列至少包含一个ZWJ,其余为emoji-sequences.txt

请注意,并非emoji-zwj-sequences.txt中的所有cps都与ZWJ粘在一起,例如,此行:

1F469 1F3FD 200D 1F4BB                      ; Emoji_ZWJ_Sequence  ; woman technologist: medium skin tone                           #  8.0  [1] (‍)

artist部分添加了ZWJ。女人和肤色部分没有任何其他cp连接。

如果您需要ZWJ,有一些启发式方法可以找出答案。如果您看到emoji-data.txt的末尾,您会看到,肤色修饰符具有属性Emoji_Modifier。如果它具有Emoji_Modifier_Base属性,则将它们定义为简单地更改先前表情符号的外观。

下一个块Emoji_Components也可以在没有ZWJ的情况下以某种方式组合。