A string in JavaScript, and any other programming language for that matter, can be defined as a sequence of textual characters. So, converting a string into an array of characters is the logical next step. In this post, we’ll tackle 3 different ways you can use to do just that.
Method1: the split() function
When it comes to converting a string into an array of characters, the split() function is probably the most widely used solution in JavaScript:
Code:
const str = 'Hello, World!';
const chars = str.split('');
console.log(chars);
Output:
[
'H', 'e', 'l', 'l', 'o', ',' , ' ', 'W', 'o', 'r', 'l', 'd','!'
]
Method 2: the spread syntax
The spread operator (…) is a new addition to the ES6. It allows you to unpack iterable objects such as arrays, sets, strings, and maps into a list of single elements. We can apply this operator to spread a string into individual characters:
Code:
const str = "Let's spread this string";
const chars = [...str];
console.log(chars);
Output:
[
'L', 'e', 't', "'", 's',
' ', 's', 'p', 'r', 'e',
'a', 'd', ' ', 't', 'h',
'i', 's', ' ', 's', 't',
'r', 'i', 'n', 'g'
]
Method 3: the Array.from() function
The Array.from() method returns a new array instance from any iterable or array-like object that has a length property. let’s apply this function to a string:
Code:
const str = 'The last example';
const chars = Array.from(str);
console.log(chars);
Output:
[
'T', 'h', 'e', ' ',
'l', 'a', 's', 't',
' ', 'e', 'x', 'a',
'm', 'p', 'l', 'e'
]
Conclusion:
There you have it, three simple ways you can use to split a string into an array of characters. Which one to choose? It comes down to your preferences.