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', '😀' ]
More Fundamentals Tutorials
- How to Add 2 Arrays Together in JavaScript
- The String `match()` Function in JavaScript
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript