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

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

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 Relatório

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 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