Splitting strings and keeping the separator in JavaScript

Josh Sherman
2 min read
Software Development JavaScript

When splitting strings, the majority of the time, I don’t care about the separator (or delimiter), just the strings that exist between it.

In JavaScript, that’s very simply with .split():

'one,two,three,four,five'.split(',');

Which will yield an array of strings like this:

['one', 'two', 'three', 'four', 'five']

Great! But if we want to keep the separator in the mix, we’ll need to venture using using regularly expressions (RegExp) instead of a string. Not just that, we’ll need to decide how we’d like to handle the separator.

First, we can treat the separator as it’s own element in the resulting array. To do so, we will need to surround the separator in parenthesis:

'one,two,three,four,five'.split(/(,)/);

Resulting in an array like this:

['one', ',', 'two', ',', 'three', ',', 'four', ',', 'five']

If you’d prefer to keep the separator combined with the other strings instead of as stand-alone elements, we have two ways to approach it. First, we can keep the separator attached to the string it was following:

'one,two,three,four,five'.split(/(?<=,)/);

Giving you an array like this:

['one,', 'two,', 'three,', 'four,', 'five']

Or, with a slight modification, we can include the separator with the string that comes after it:

'one,two,three,four,five'.split(/(?=,)/);

Similar output, but with no separator in the first element:

['one', ',two', ',three', ',four', ',five']
Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Related Articles