Split a string with a regex in JavaScript
Intermediate · 4 min read
Text typed by people is messy. Someone writes 'rice , beans,yam' with spaces in odd places, and a plain split(',') hands those spaces back to you inside every field. You could trim each piece afterwards, but split can do it all in one go if you give it a pattern instead of a fixed separator.
In this tutorial you will split messy text with a regular expression, learn what the second argument of split (the limit) really does, and see a surprising effect of brackets in the pattern. You should know how split(',') works. The regular expression parts are explained from scratch below.
A tiny regular expression primer
A regular expression, or regex, is a pattern that describes text. In JavaScript you write it between slashes, like /,/, which matches a comma. A few symbols are enough for this exercise:
\smatches one whitespace character: a space, a tab or a newline.*after something means "zero or more of it". So\s*matches no spaces, one space or many.+means "one or more". So\s+matches a run of at least one whitespace character.[0-9]matches one digit.
split accepts a pattern
Anywhere you can pass a string separator to split, you can pass a regex instead. Then split cuts wherever the pattern matches, and throws away whatever it matched.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
23 Split on a pattern, and split with a limit
fairSplit 'rice , beans,yam' into clean fields with one call, using a pattern that absorbs the surrounding spaces. Then find out what the limit argument really does.
Stuck? Three hints, smallest first
- 1. A regular expression separator can match the comma and any whitespace either side of it.
- 2. The limit caps the number of fields returned; it does not put the rest in the last one.
- 3. A capture group inside the separator is kept in the output, which is occasionally exactly what you want.
Step 1: the plain comma leaves the spaces
const line = 'rice , beans,yam';
console.log(line.split(',')); // [ 'rice ', ' beans', 'yam' ]
The commas are gone but the spaces around them stayed. 'rice ' with a trailing space won't equal 'rice' in a comparison.
Step 2: a pattern that swallows the spaces
The separator we really want is "any spaces, a comma, any spaces". In regex that is \s*,\s*:
const line = 'rice , beans,yam';
console.log(line.split(/\s*,\s*/)); // [ 'rice', 'beans', 'yam' ]
The spaces are now part of what matched, so they are thrown away with the comma. The * matters: between beans and yam there are no spaces at all, and \s* is happy to match zero of them.
Step 3: split on runs of whitespace
Words separated by one space, three spaces or a tab can all be split with \s+:
console.log('a b\tc'.split(/\s+/)); // [ 'a', 'b', 'c' ]
console.log(' a b'.split(/\s+/)); // [ '', 'a', 'b' ]
The second line has a surprise. The text starts with a space, so the pattern matches at the very start, and a match at the start means there is an (empty) field before it.
Step 4: trim first
The fix is to remove the spaces at both ends before splitting:
console.log(' a b '.trim().split(/\s+/)); // [ 'a', 'b' ]
trim() belongs in front of nearly every whitespace split.
Step 5: what the limit really does
split takes an optional second argument, a number. Many people expect it to mean "split into at most this many pieces, and keep the rest together in the last one". It doesn't:
console.log('a,b,c,d'.split(',', 2)); // [ 'a', 'b' ]
You get the first two pieces, and c and d are thrown away. The limit only caps how many items come back.
Step 6: keep the rest yourself
If you want the first field on its own and everything else together, split fully, then join the tail back up:
const parts = 'a,b,c,d'.split(',');
console.log([parts[0], parts.slice(1).join(',')]); // [ 'a', 'b,c,d' ]
parts.slice(1) is every item after the first, and join(',') puts their commas back.
Step 7: brackets in the pattern are kept
Round brackets in a regex make a capture group: they mark part of the match to remember. In split, a captured part is put into the result between the pieces:
console.log('a1b2c'.split(/[0-9]/)); // [ 'a', 'b', 'c' ]
console.log('a1b2c'.split(/([0-9])/)); // [ 'a', '1', 'b', '2', 'c' ]
Without brackets the digits vanish, as separators always do. With brackets they come back. That is handy when you need to keep the separators, for example splitting a sum like '3+4-1' while keeping the + and -.
The full solution
Here is the complete answer: the messy line split with a pattern, the limit, the capture group and the trim habit, each with a check. Press Run and compare the printed arrays.
const line = 'rice , beans,yam';
console.log('split(/\\s*,\\s*/) :', line.split(/\s*,\s*/));
console.log("split(',') :", line.split(','), '<- the spaces came along');
console.log("'a,b,c,d'.split(',', 2) :", 'a,b,c,d'.split(',', 2), '<- c and d are DISCARDED');
console.log("'a1b2c'.split(/([0-9])/) :", 'a1b2c'.split(/([0-9])/), '<- the group is kept');
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('a pattern separator can absorb the spaces around the comma', line.split(/\s*,\s*/), ['rice', 'beans', 'yam']);
test('a plain comma leaves them behind', line.split(','), ['rice ', ' beans', 'yam']);
test('the limit caps how many fields come back', 'a,b,c,d'.split(',', 2), ['a', 'b']);
test('the remainder is DISCARDED, not returned as a tail', 'a,b,c,d'.split(',', 2).length, 2);
test('so slice and rejoin when you want the rest', (() => { const p = 'a,b,c,d'.split(','); return [p[0], p.slice(1).join(',')]; })(), ['a', 'b,c,d']);
test('a capture group in the separator is KEPT in the output', 'a1b2c'.split(/([0-9])/), ['a', '1', 'b', '2', 'c']);
test('without the group the digits vanish', 'a1b2c'.split(/[0-9]/), ['a', 'b', 'c']);
test('splitting on whitespace handles runs of it', 'a b\tc'.split(/\s+/), ['a', 'b', 'c']);
test('but a leading space then gives an empty first field', ' a b'.split(/\s+/), ['', 'a', 'b']);
test('which is why trim comes first', ' a b '.trim().split(/\s+/), ['a', 'b']);
limit is not "split into at most n pieces, keeping the rest together" — that is what it looks like and what people assume. It throws the remainder away. If you want 'key=a=b' split into ['key', 'a=b'], use indexOf and two slices, or split fully and rejoin the tail.
The empty first field from ' a b'.split(/\s+/) is the reason trim() belongs in front of nearly every whitespace split. The separator matched at position 0, and a match at position 0 means there is a field before it.
Common mistakes
- Using
*where you mean+for word splits.'ab cd'.split(/\s*/)gives[ 'a', 'b', 'c', 'd' ], because\s*also matches the empty gap between two letters. Use\s+to split on whitespace. - Expecting the limit to keep the remainder. It discards it. Split fully and rejoin the tail.
- Skipping
trim(). Leading or trailing whitespace gives you an empty first or last field.
Try it yourself
- Split
'red; green ;blue'into three clean color names with onesplitcall. - Split
'key=a=b'into['key', 'a=b']. - Split
'3+4-1'so the result is['3', '+', '4', '-', '1'].