Normally I would just use something like str[i]
.
But what if str = "βοΈππΌ"
?
str[i]
fails. for (x of str) console.log(x)
also fails. It prints out a total of 4 characters, even though there are clearly only 2 emoji in the string.
What's the best way to iterate over every character I can see in a string (and newlines, I guess), and nothing else?
The ideal solution would return an array of 2 characters: the 2 emoji, and nothing else. The claimed duplicate, and a bunch of other solutions I've found, don't fit this criteria.
for...of
syntax which I pointed out does not work in this case. But please correct me if I'm wrong! β Schottischefor..of
cannot be polyfilled." The suggested answers shows how to split a string into code points. If you don't want to polyfill it, then just use it as a free function. β MythicizetoCodePoints
function returns an array of length 4. β Schottischefor (x in str) console.log(x)
prints six characters (plus additional junk not relevant to the discussion), not the four you originally claimed. That's because the string"βοΈππΌ"
is six code units long:"\u2600\ufe0f\ud83d\ude4c\ud83c\udffc"
. This breaks down into four code points: U+2600 (BLACK SUN WITH RAYS), U+FE0F (VARIANT SELECTOR 16), U+1F64C (PERSON RAISING BOTH HANDS IN CELEBRATION), and U+1F3FC (EMOJI MODIFIER FITZPATRICK TYPE 3). It sounds like you are looking to break into graphemes, which is a harder problem. β Mythicizefor (x of str)
notx in str
specifically becauseof
breaks on code points rather than characters. Graphemes turned out to be the magic word here though - once I googled for that I quickly found a decent library to get the job done. β Schottische