Split a string into an array in JavaScript
Beginner · 4 min read
Data often arrives as one long piece of text: a line from a CSV file, a list of tags typed into a form, a row copied from a spreadsheet. Before you can work with the parts, you need to cut the text up. In JavaScript that job belongs to split.
In this tutorial you will turn 'rice,beans,yam' into an array, then try the edge cases that trip people up: a separator that isn't there, separators at the ends, and an empty string. You should know what a string and an array are.
What split does
text.split(separator) looks for the separator inside text, cuts at every place it finds it, and gives back an array of the pieces in between. The separator itself is thrown away.
console.log('a-b-c'.split('-')); // [ 'a', 'b', 'c' ]
The original string is not changed. Strings in JavaScript can't be changed once they exist, so split always makes a new array.
The opposite of split
array.join(separator) does the reverse: it glues the pieces back together with the separator between them. If you split and join with the same separator, you get the original text back. Keeping that pair in mind makes the edge cases below easier to predict.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
22 Split on a separator
easyTurn 'rice,beans,yam' into an array. Then split on a separator that is not there, on nothing at all, and split an empty string.
Stuck? Three hints, smallest first
- 1.
splitreturns an array; the separator itself is not included. - 2. A separator that never matches gives a one-element array containing the whole string.
- 3. An empty string behaves differently depending on whether the separator is
''or something else.
Step 1: split on a comma
const csv = 'rice,beans,yam';
console.log(csv.split(',')); // [ 'rice', 'beans', 'yam' ]
Three pieces, and no commas left in any of them. That is the everyday case.
Step 2: a separator that isn't there
What if you split on a semicolon, but the text uses commas?
const csv = 'rice,beans,yam';
console.log(csv.split(';')); // [ 'rice,beans,yam' ]
console.log(csv.split()); // [ 'rice,beans,yam' ]
There is nowhere to cut, so you get an array with one item: the whole string. Calling split() with no separator at all does the same. No error is thrown, so if your output looks like one big field, check the separator first.
Step 3: separators at the edges and side by side
console.log('a,b,'.split(',')); // [ 'a', 'b', '' ]
console.log(',a'.split(',')); // [ '', 'a' ]
console.log('a,,b'.split(',')); // [ 'a', '', 'b' ]
Every comma means "a field ends here and a new one starts". A comma at the end leaves an empty field after it. A comma at the start leaves an empty field before it. Two commas in a row leave an empty field between them.
This is not a bug. In a CSV file, a,,b really does have three columns with a blank one in the middle. Remove the empty strings only when you know they are noise, for example with .filter((s) => s !== '').
Step 4: splitting an empty string
This is the case that catches people out:
console.log(''.split(',')); // [ '' ]
console.log(''.split(',').length); // 1
console.log(''.split('')); // []
Splitting an empty string on a comma gives one empty field, not zero. There was no comma to cut at, so, as in Step 2, you get the whole string back in an array, and the whole string is empty. Splitting on '' (nothing) is different: it splits into single characters, and an empty string has none, so the array is empty.
Why does it matter? A quick "count the items" function written as text.split(',').length reports 1 for an empty input. If empty input is possible, check for it before splitting.
Step 5: a longer separator
The separator can be more than one character:
console.log('a -> b -> c'.split(' -> ')); // [ 'a', 'b', 'c' ]
The spaces are part of the separator, so they disappear too.
Step 6: join puts it back
const csv = 'rice,beans,yam';
console.log(csv.split(',').join(',')); // 'rice,beans,yam'
console.log(csv.split(',').join(',') === csv); // true
Split and join with the same separator undo each other.
The full solution
Here is the complete answer: the normal split, the missing separator, both empty-string cases, and checks for the edge cases above. Press Run and compare each printed array with the steps.
const csv = 'rice,beans,yam';
console.log("split(',') :", csv.split(','));
console.log("split(';') :", csv.split(';'), '<- no match, so one element');
console.log("''.split(','):", ''.split(','), '<- one EMPTY element');
console.log("''.split(''):", ''.split(''), '<- no elements at all');
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('split on a comma gives the fields', csv.split(','), ['rice', 'beans', 'yam']);
test('a separator that is not there gives one element', csv.split(';'), ['rice,beans,yam']);
test('no separator at all also gives one element', csv.split(), ['rice,beans,yam']);
test('a trailing separator produces an empty last field', 'a,b,'.split(','), ['a', 'b', '']);
test('and a leading one an empty first field', ',a'.split(','), ['', 'a']);
test('consecutive separators leave empties between them', 'a,,b'.split(','), ['a', '', 'b']);
test('splitting an empty string on a comma gives ONE empty field', ''.split(','), ['']);
test('but splitting it on nothing gives no fields at all', ''.split(''), []);
test('a multi-character separator works', 'a -> b -> c'.split(' -> '), ['a', 'b', 'c']);
test('split and join are inverses with the same separator', csv.split(',').join(','), csv);
The two empty-string cases are the ones that bite. ''.split(',') is [''] — length 1 — so a naive "count the fields" or "count the words" function reports 1 for empty input. ''.split('') is []. Exercise 35 handles the consequence.
Empty fields from leading, trailing and doubled separators are not a bug either: they are the honest answer for CSV, where a,,b genuinely has three columns and the middle one is blank. Filter them out only when you know they are noise.
Common mistakes
- Counting fields on empty input.
''.split(',').lengthis 1, not 0. Checktext === ''first. - Using the wrong separator. Splitting on
', 'when the data is'a,b'(no space) gives one field. Look at the actual text. - Forgetting the spaces.
'a, b'.split(',')gives'a'and' b'with a leading space. Trim each piece, or split on a pattern (the next exercise).
Try it yourself
- Split
'2025-04-09'into year, month and day, and turn each piece into a number. - Split
'red,,green,'and remove the empty strings so only the colors are left. - Write
countItems(text)that returns 0 for''and the number of comma-separated items otherwise.