1

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."]

user44109
  • 121
  • 6
  • Duplicate: [Javascript and regex: split string and keep the separator](https://stackoverflow.com/questions/12001953/javascript-and-regex-split-string-and-keep-the-separator) –  Aug 09 '22 at 22:48
  • @ChrisG Not really a duplicate, I read the answer you refer to before posting but couldn't find info regarding the ordering part (only about multiple separators and keeping the separators) – user44109 Aug 09 '22 at 22:57

1 Answers1

2

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);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you, that was fast and worked perfectly! I will accept this answer as soon as Stack Overflow let's me (in 9 mins)! – user44109 Aug 09 '22 at 22:43