How to Split a String to an Array in JavaScript

To split a string into an array in JavaScript we can use the split() method. In this tutorial, we will look at some of the different ways we can use split() to create an array containing substrings from the original string.

 

No Separator

To turn the whole string into an array containing one element, don't put anything inside the () (parenthesis) of the split() method.

 

var str = 'oranges';

var array = str.split();

console.log(array);
["oranges"]

 

Split Every Character into an Array Element

To make every character in a string an element in an array we can pass an empty string ('') into the split() method.

 

var str = 'oranges';

var array = str.split('');

console.log(array);
["o", "r", "a", "n", "g", "e", "s"]

 

Split by Each Matching Substring

Let's say we had a comma-separated list in a string that needed to be split into an array by commas. We could do this:

 

var str = 'oranges, apples, pears, melons';

var array = str.split(', ');

console.log(array);
["oranges", "apples", "pears", "melons"]

 

note - you will also see that the (comma and space) are automatically omitted from the new array.

 

Limit The Elements to Return From split()

You can pass the number of elements to limit split() to in the second argument.

 

var str = 'oranges, apples, pears, melons';

var array = str.split(', ', 2);

console.log(array);
["oranges", "apples"]

 

Conclusion

You now know how to split strings into arrays in JavaScript.

string array split