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

(You will need Firefox or Safari to see emoji in code.)

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

In JavaScript, "πŸ˜΄πŸ˜„πŸ˜ƒβ›”πŸŽ πŸš“πŸš‡".length == 13 , because "β›”" length is 1, the rest is 2. Therefore, we cannot do

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

Here is what I did: emoji poster

+8
javascript unicode emoji
source share
3 answers

Edit: see Orlin Georgiev answer for the correct solution in the library: https://github.com/orling/grapheme-splitter


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

 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 [ "😴", "πŸ˜„", "πŸ˜ƒ", "β›”", "🎠", "πŸš“", "πŸš‡" ] 
+15
source share

JavaScript ES6 has a solution! For real separation:

 [..."πŸ˜΄πŸ˜„πŸ˜ƒβ›”πŸŽ πŸš“πŸš‡"] // ["😴", "πŸ˜„", "πŸ˜ƒ", "β›”", "🎠", "πŸš“", "πŸš‡"] 

Yay Except for the fact that when you run this through your transporter, it may not work (see @brainkim Comment). It only works on initial launch in a browser compatible with ES6. Fortunately, this applies to most browsers (Safari, Chrome, FF), but if you are looking for high browser compatibility, this is not the solution for you.

+4
source share

The splitter graph library that does just that is fully compatible even with older browsers and works not only with emojis, but also with all exotic characters: https://github.com/orling/grapheme-splitter You will probably miss the extreme cases in any home brew solution. It is actually based on the Unicode UAX-29 standard

+3
source share

All Articles