Convert a String to an Array in JavaScript
Mar 31, 2021
JavaScript strings have a built-in split()
method that split a string by instances of a given separator. For example, here's how you can split
a string by dashes:
const str = 'kebab-case-string';
str.split('-'); // ['kebab-case-string']
Or you can split a string by commas:
const str = '0,1,2';
str.split(','); // ['0', '1', '2']
Converting to a Character Array
There are numerous ways to convert a string to an array of characters. With an empty string as the separator, the split()
function will return an array of characters:
'Hello'.split(''); // ['H', 'e', 'l', 'l', 'o']
However, this approach has a problem because of how split()
handles UTF-16 characters. For example, emojis end up with incorrect results:
'Hello😀'.split(''); // ['H', 'e', 'l', 'l', 'o', '�', '�']
The Array.from()
function handles UTF-16 characters. You should use Array.from()
if you're looking to split a string into an array of characters and expect UTF-16 characters.
Array.from('Hello😀'); // [ 'H', 'e', 'l', 'l', 'o', '😀' ]
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!