Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

248
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda