Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over only the characters in a string I can actually see?

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.

like image 707
thedayturns Avatar asked Apr 22 '16 04:04

thedayturns


People also ask

Can you use a for loop to iterate over the characters in a string?

A for loop is flexible enough to change how looping over characters in a string is performed. For example, the loop could be quickly modified to start and end at a specific point in the string by simply changing the initializer and conditional expressions of the for loop.

Can you loop through the characters in a string python?

Looping through a string One way to iterate over a string is to use for i in range(len(str)): . In this loop, the variable i receives the index so that each character can be accessed using str[i] .


1 Answers

I eventually found the answer in the form of this insane JS library:

https://github.com/orling/grapheme-splitter

like image 123
thedayturns Avatar answered Sep 26 '22 14:09

thedayturns