How to Convert a String Into an Array of Characters

The split string method, Unicode characters, Array.from utility

Cristian Salcescu
Frontend Essentials

--

Photo by the author

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.

--

--