Home > OS >  Split string using multiple separators and keep the separators in the result
Split string using multiple separators and keep the separators in the result

Time:08-10

I'm trying to split strings into an array if there is a semicolon ";" or a dot "." or a colon ":".

The problem is, I would like the split to happen right after the separator, not before it. This code is working otherwise, but the separator is in the beginning of each element in the array. How can I make the separator become the last character in the array element?

const arrayForSplitText = myString.split((/(?=[.;:])/gi));

Example:

myString = "Hello there. I would like this: split me with the separators at the end of each element."

current result:

["Hello there", ". I would like this", ": split me with the separators at the end of each element", "."]

desired result:

["Hello there.", "I would like this:", "split me with the separators at the end of each element."]

CodePudding user response:

Instead of looking ahead for the separator, look behind for it. Since it looks like you want the spaces after the separator gone too if they exist, add an optional space too.

const myString = "Hello there. I would like this: split me with the separators at the end of each element."
const arrayForSplitText = myString.split(/(?<=[.;:]) ?/gi);
console.log(arrayForSplitText);

If you can't use lookbehind, .match for anything but the separators, followed by the separators, works too.

const myString = "Hello there. I would like this: split me with the separators at the end of each element."
const arrayForSplitText = myString.match(/[^.;:] [.;:]/g);
console.log(arrayForSplitText);

To also trim out the leading spaces with .match will require a slightly longer pattern.

const myString = "Hello there. I would like this: split me with the separators at the end of each element."
const arrayForSplitText = myString.match(/[^.;: ][^.;:]*[.;:]/g);
console.log(arrayForSplitText);

  • Related