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.
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.
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] .
I eventually found the answer in the form of this insane JS library:
https://github.com/orling/grapheme-splitter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With