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

170
Vistas
RegExp / JavaScript: Split string on multiple characters, keep separators without using lookbehind

Let's say I have a string: "This is a string-thing". I want to split on both space and hyphen, but keep the separators together with the previous word => ["This ", "is ", "a ", "string-", "thing"]

I'm currently doing this using the following regExp:

string.split(/(?<=[\s-])/g)

This does what is supposed to.. at least in Chrome. As I understand Safari doesn't support lookbehind in regExp which breaks the code. Is there any way to do this without lookbehind?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could match the words without lookbehind.

const
    string = "This is a string-thing",
    parts = string.match(/.+?([\s-]|$)/g);

console.log(parts);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You might also use split with a capture group to keep the value to split on, and remove the empty entries from the resulting array.

The pattern matches

  • ( Capture group 1
    • [^\s-]* Repeat 0+ times matching any char other than a whitespace char or -
    • [\s-] Match either a whitespace char or -
  • ) Close group 1

Note that \s can also match a newline.

const s = "This is a string-thing";
const regex = /([^\s-]*[\s-])/;
console.log(s.split(regex).filter(Boolean));

about 4 years ago · Juan Pablo Isaza 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