How can I split a string containing emoji into an array?

柔情痞子 提交于 2019-11-27 01:26:36

问题


(You'll need Firefox or Safari to see the emoji in the code.)

I want to take a string of emoji and do something with the individual characters.

In JavaScript "😴😄😃⛔🎠🚓🚇".length == 13 because "⛔" length is 1, the rest are 2. So we can't do

s = string.split(""); 
c = [];
c[0] = s[0]+s[1];

Here's what I made:


回答1:


The grapheme-splitter library that does just that, is fully compatible even with old browsers and works not just with emoji but all sorts of exotic characters: https://github.com/orling/grapheme-splitter You are likely to miss edge-cases in any home-brew solution. This one is actually based on the UAX-29 Unicode standart




回答2:


Edit: see Orlin Georgiev's answer for a proper solution in a library: https://github.com/orling/grapheme-splitter


Thanks to this answer I made a function that takes a string and returns an array of emoji:

var emojiStringToArray = function (str) {
  split = str.split(/([\uD800-\uDBFF][\uDC00-\uDFFF])/);
  arr = [];
  for (var i=0; i<split.length; i++) {
    char = split[i]
    if (char !== "") {
      arr.push(char);
    }
  }
  return arr;
};

So

emojiStringToArray("😴😄😃⛔🎠🚓🚇")
// => Array [ "😴", "😄", "😃", "⛔", "🎠", "🚓", "🚇" ]



回答3:


JavaScript ES6 has a solution!, for a real split:

[..."😴😄😃⛔🎠🚓🚇"] // ["😴", "😄", "😃", "⛔", "🎠", "🚓", "🚇"]

Yay? Except for the fact that when you run this through your transpiler, it might not work (see @brainkim's comment). It only works when natively run on an ES6-compliant browser. Luckily this encompasses most browsers (Safari, Chrome, FF), but if you're looking for high browser compatibility this is not the solution for you.



来源:https://stackoverflow.com/questions/24531751/how-can-i-split-a-string-containing-emoji-into-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!