46

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(""); 
console.log(s);
forresto
  • 12,078
  • 7
  • 45
  • 64

7 Answers7

33

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.

Downgoat
  • 13,771
  • 5
  • 46
  • 69
  • 1
    Babel with es6 settings will transpile this into a call to String's iterator function so it does work in some transpilers. – brainkim Nov 01 '16 at 02:58
  • @brainkim I specified that in the answer. It is the fault of the transpiler for not meeting the standard on this – Downgoat Nov 01 '16 at 03:05
  • Ah, I'm saying it sometimes works. "when you run this through your transpiler, it won't work" implies it never works. It's dependent on what specific emojis are in the string, the transpiler you're using, etc. – brainkim Nov 01 '16 at 05:05
  • 38
    `[...'‍‍‍'] // ["", "‍", "", "‍", "", "‍", ""]` – BrunoLM May 15 '18 at 17:22
  • 10
    `[...""] // ["", ""]` – JJJ Dec 05 '18 at 22:57
27

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 [ "", "", "", "⛔", "", "", "" ]
Community
  • 1
  • 1
forresto
  • 12,078
  • 7
  • 45
  • 64
  • 4
    noting that this won't work for emoji that use zero-width joiners, variation selectors, or the keycap emoji which are digit + keycap + variation selector – Beau Nov 11 '15 at 07:39
  • Just use the `match` method `str.match(/([\uD800-\uDBFF][\uDC00-\uDFFF])/);` and it'll return the emojis – Edwin Reynoso Nov 08 '16 at 00:38
  • I tried you function and it works for me, but look at this: emojiStringToArray("⛔❤️❤️❤️❤️❤️❤️") // => Array [ "", "", "", "⛔", "", "", "", "❤️❤️❤️❤️❤️❤️" ] Do you know how to solve this error? – Sebastián Lara Jan 25 '17 at 20:07
  • 15
    `emojiStringToArray( '‍‍‍' ) // ["", "‍", "", "‍", "", "‍", ""]` – BrunoLM May 15 '18 at 17:21
23

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.

rootEnginear
  • 231
  • 2
  • 4
21

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

Orlin Georgiev
  • 1,391
  • 16
  • 18
13

The modern / proper way to split a UTF8 string is using Array.from(str) instead of str.split('')

Ruben Reyes
  • 745
  • 6
  • 8
  • 1
    This is awesome. By them MDN provides a polyfill for this as well. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from – Hooman Askari Jul 27 '20 at 11:10
  • 10
    Sadly, this doesn't work as expected with compound ones: `Array.from('‍‍‍'); // [ "", "‍", "", "‍", "", "‍", "" ]` `Array.from(''); // [ "", "" ]` – forresto Nov 25 '20 at 13:09
10

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.

Matt Davies
  • 136
  • 1
  • 6
  • Until `Intl.Segmenter` gets Firefox support (https://caniuse.com/mdn-javascript_builtins_intl_segmenter), I think that this is the best answer. – forresto Sep 22 '22 at 06:46
8

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)
ArtEze
  • 186
  • 1
  • 5
  • 17