Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

247
Views
Split string using multiple separators and keep the separators in the result

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!