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

87
Vistas
JavaScript String insert newline before every occurrence of delimiter from list

In JavaScript, how do I insert a newline character before every occurrence of a delimiter from a list of delimiters?

Example:

const delimiters = ['Q) ', 'A) ', 'B) ', 'C) ', 'E) ']
const str = 'Some textC) Some textE) Some text'

I want to create the String:

Some text
C) Some text
E) Some text
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can solve this with a cheeky .replaceAll and simple strings instead of regex 🚀

const delimiters = ['Q) ', 'A) ', 'B) ', 'C) ', 'E) '];
const start  = 'Some textC) Some textE) Some text';

let output = start;
for (const str of delimiters) {
  output = output.replaceAll(str, "\n"+str);
}

console.log(output);

about 4 years ago · Juan Pablo Isaza Denunciar

0

The first answer posted gives the simplest and best solution I believe, but here is an example of doing it with a regular expression.

const delimiters = ['Q) ', 'A) ', 'B) ', 'C) ', 'E) ']
const str = 'Some textC) Some textE) Some text';

const pattern = `(?=${delimiters.join('|').replaceAll(')', '\\)')})`;
console.log(`Pattern: "${pattern}"`); 

console.log(str.replace(new RegExp(pattern, 'g'), '\n'));

Note that care should be taken to escape any characters in the delimiters that have special meaning in a regular expression.

Above, I just use .replaceAll(')', '\\)') to escape the ) after joining the delimiters with the regex alternation character | in a positive lookahead (?=alternative1|alternative2|etc) before passing it to the RegExp constructor.

Note also that this method of joining with | would not result in a reliably working regular expression if a delimiter itself contained the | character.

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