Splitting strings and keeping the separator in 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():


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:


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:


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:


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

['one', ',two', ',three', ',four', ',five']
Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.