How to get all characters in a string?
…and people arguing if you should use
str.charAt() or the bracket notation.
However, these answers are usually pretty old and don’t take into account one important issue with these solutions…
🔥 Emoji ☠️
This can make the above methods sometimes return incorrect results, like this:
ES6 to the rescue!
ES6 introduced the concept of iterators and along with it, a solution to the surrogate pairs problem.
Here are 4 ways to correctly get all characters in a string:
The simplest way to create an array from any iterable, including strings.
The shortest way to do get an array from a string, but sacrifices readability.
The most versatile and performant of the bunch.
RegExp unicode flag
If you’re feeling fancy you can also use a regular expression with the unicode flag.
All of the above are ES6 features, which at this time is supported pretty much everywhere, with the exception of internet explorer. If you need to support internet explorer you should transpile your code with a tool like Babel. Or just use one of the old methods, but be aware of their limitations.
Thanks for reading.
If you know other clever ways to turn strings into character arrays, let me know in the comments, I always like learning new things.
Complete Guide to CSS Gradients
Gradients are making a comeback, make sure you know how to use them
An in depth guide to FileReader API and object URLs.