How to Convert a String Into an Array of Characters
The split string method, Unicode characters, Array.from utility

In this short post, we will discuss how to convert strings into an array of characters and how to handle the special case of characters taking more the 16-bits.
There is no char type in JavaScript. A character is still a string containing a single character.
split
To convert a string into an array storing all its characters we can use the split method for example.
const word = 'Lannister';
const chars = word.split('');
//["L", "a", "n", "n", "i", "s", "t", "e", "r"]Strings are store in UTF-16 units in JavaScript. The split method works well for all characters fitting in 16 bits but has issues when trying to split a character that takes more than that, like an emoji. Consider the following example.
const word = 'Hi🙂';
const chars = word.split('');
//["H", "i", "�", "�"]Instead of getting the emoji as the third element in the new array, we got to unrecognizable characters.
Also, the str.length property is wrong in this case. It says 4.
str.length gives the count of UTF-16 units.
word.length
//4Array.from
There is another utility that can help in this scenario the Array.from.
The Array.from utility creates a new array from an array-like object.
const word = 'Lannister';
const chars = Array.from(word);
//["L", "a", "n", "n", "i", "s", "t", "e", "r"]It handles the case when the characters take more than 16-bit.
const word = 'Hi🙂';
const chars = Array.from(word);
//["H", "i", "🙂"]Spread Syntax
The spread syntax can also be used to convert a string into an array of characters. Below is an example of converting a string made of common characters.
const word = 'Lannister';
const chars = [ ...word ];
//["L", "a", "n", "n", "i", "s", "t", "e", "r"]The conversions works also when some characters take more than 16-bit.
const word = 'Hi🙂';
const chars = [...word];
//["H", "i", "🙂"]To get the correct number of characters in a string containing chars using more the 16-bit we need to convert it into an array, with one of the previous valid methods, and check the length of the new array [...str].length .

Thanks for reading.
