简体   繁体   中英

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

(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

 var string = "😴😄😃⛔🎠🚓🚇"; s = string.split(""); c = []; c[0] = s[0]+s[1]; console.log(c);

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.

["

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


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;
};

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

拆分 UTF8 字符串的现代/正确方法是使用Array.from(str)而不是str.split('')

It can be done using the u flag of a regular expression. The regular expression is:

/.*?/u

This is broken every time there are there are at least minimally zero or more characters that may or may not be emojis, but cannot be spaces or new lines break.

  • There are at least minimally zero or more: ? (split in zero chars)
  • Zero or more: *
  • Cannot be spaces or new line break: .
  • May or may not be emojis: /u

By using the question mark ? I am forcing to cut exactly every zero chars, otherwise /.*/u it cuts by all characters until I find a space or newline break.

 var string = "😴😄😃⛔🎠🚓🚇" var c = string.split(/.*?/u) console.log(c)

With the upcoming Intl.Segmenter . You can do this:

const splitEmoji = (string) => [...new Intl.Segmenter().segment(string)].map(x => x.segment)

splitEmoji("😴😄😃⛔🎠🚓🚇") // ['😴', '😄', '😃', '⛔', '🎠', '🚓', '🚇']

This also solve the problem with "👨‍👨‍👧‍👧" and "👦🏾".

splitEmoji("👨‍👨‍👧‍👧👦🏾") // ['👨‍👨‍👧‍👧', '👦🏾']

According to CanIUse , apart from IE and Firefox, this can be use 84.17% globally currently .

The Grapheme Splitter library by Orlin Georgiev is pretty amazing.

Although it hasn't been updated in a while and presently (Sep 2020) it only supports Unicode 10 and below.

For an updated version of Grapheme Splitter built in Typescript with Unicode 13 support have a look at: https://github.com/flmnt/graphemer

Here is a quick example:

import Graphemer from 'graphemer';

const splitter = new Graphemer();

const string = "😴😄😃⛔🎠🚓🚇";

splitter.countGraphemes(string); // returns 7

splitter.splitGraphemes(string); // returns array of characters

The library also works with the latest emojis.

For example "👩🏻‍🦰".length === 7 but splitter.countGraphemes("👩🏻‍🦰") === 1 .

Full disclosure: I created the library and did the work to update to Unicode 13. The API is identical to Grapheme Splitter and is entirely based on that work, just updated to the latest version of Unicode as the original library hasn't been updated for a couple of years and seems to be no longer maintained.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM