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

185
Visualizações
Split a string by space but keep space after reach element - Javascript

I am trying to split a string by space but keep the space after each element. So 'This is a string' would become ['This ', 'is ', 'a ', 'string']. The input string could contain words, numbers, or special characters.

Right now I have:

var words = text.split(/(\w+\s)/).filter(x => x !== '');

The above works, but the regex split gives you ['This ', '', 'is ', '', 'a ', '', 'string'] and requires use of .filter to delete the empty string elements. I bet there is a better regex, but I'm not familiar enough with regex to figure it out.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use a lookbehind as the regular expression to split on, so that the delimiter doesn't use any characters in the string.

const text = 'This is a   string';
const words = text.split(/(?<=\s)/);
console.log(words);

about 4 years ago · Santiago Trujillo 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