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
const string = "π¨βπ¨βπ§βπ§ π¦πΎ π΄ π π β π π π";
const s = string.split("");
console.log(s);
const a = Array.from(string);
console.log(a);
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, this is supported by all modern browsers.
If you need to support older browsers, as mentioned in Matt Davies' answer, Graphemer is the best solution:
let Graphemer = await import("https://cdn.jsdelivr.net/npm/graphemer@1.4.0/+esm").then(m => m.default.default);
let splitter = new Graphemer();
let graphemes = splitter.splitGraphemes("π¨βπ¨βπ§βπ§π¦πΎ"); // ['π¨βπ¨βπ§βπ§', 'π¦πΎ']