Date:

Share:

Splitting strings and keeping the separator in JavaScript by Josh Sherman

Related Articles

When splitting strings, most of the time, I do not care about the separator (or separator), but only about the strings that exist between it.

In JavaScript, it’s very simple with .split():

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

Which will yield an array of strings like this:

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

big! But if we want to leave the separator in the mixture, we will have to dare to use regular expressions (RegExp) Instead of a string. Not only that, we will have to decide how we want to handle the separator.

First, we can treat the separator as its own element in the resulting array. To do this, we will need to enclose the separator in parentheses:

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

The result is such an array:

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

If you prefer to leave the separator in combination with the other strings instead of as independent elements, we have two ways to access it. First, we can leave the separator connected to the following string:

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

Gives you such an array:

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

Alternatively, with a slight change, we can include the separator with the string that comes after it:

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

Similar output, but no separator in the first element:

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

good things? Want more?

Weekly emails on technology, development and sometimes sauerkraut.

100% fresh, first-class content, never spam.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles