How to convert a string to an array
Short answer
The split() method splits a string by a separator:
console.log('red, green, blue'.split(', '));Output:
[
"red",
"green",
"blue"
]By characters
The ... operator spreads a string into individual characters:
console.log([...'code']);Output:
[
"c",
"o",
"d",
"e"
]By words
When words may be separated by several spaces, split the string with a regular expression:
console.log(' one two three '.trim().split(/\s+/));Output:
[
"one",
"two",
"three"
]Common mistake
split() without arguments does not split the string at all, it returns an array with one element:
console.log('a,b,c'.split().length);
console.log('a,b,c'.split(',').length);Output:
1
3Functions used in this recipe
- String.prototype.split — Splits a string into an array by a separator.
- Array.from — Creates an array from a string, Set, Map or another iterable.