Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda