Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 548
forresto Avatar asked Jul 02 '14 12:07

forresto


People also ask

How do you split a string into an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do I split a string into an object?

Description. In JavaScript, split() is a string method that is used to split a string into an array of strings using a specified delimiter. Because the split() method is a method of the String object, it must be invoked through a particular instance of the String class.

How do you split a string in HTML?

The <br> HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.


1 Answers

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.

like image 103
Downgoat Avatar answered Sep 19 '22 10:09

Downgoat