Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
3

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.