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

209
Visualizações
Replace array of signs inside a span

I want to wrap each sign in the given array inside a span tag to be able to render it to DOM:

Here is the signs array:

const signs = ['!!', '?!', '!?', '...', '..', '.', '?', '!', ':', '؟!', '!؟', '؟']; 

I can replace each sign individually like this:

result = result.replace(/([\:])/g, "<span class='some-class'>&nbsp;:</span>");

The above code put : sign inside a span.

How can I do this for all of array signs without hard coding them?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use

let result = "!! ?! !? ... .. . ? ! : ؟!, !؟ ؟";
const signs = ['!!', '?!', '!?', '...', '..', '.', '?', '!', ':', '؟!', '!؟', '؟']; 
signs.sort((a, b) => b.length - a.length);
const regex = new RegExp(signs.map(x => 
    x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|'),
    'g');
result = result.replace(regex, "<span class='some-class'>&nbsp;$&</span>");
console.log(result)

Here,

  • signs.sort((a, b) => b.length - a.length) sorts the signs array items by length in descending order
  • signs.map(x => x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')) - escapes all the special chars in the items to make them match literal chars inside a regex
  • ....join('|') - creates an alternation regex
  • new RegExp(..., 'g') - defines a RegExp object that matches all pattern occurrences in the string
  • $& in the replacement pattern inserts the match value.
about 4 years ago · Juan Pablo Isaza Relatório

0

You could use:

result = signs.map(sign => "<span class='some-class'>&nbsp;" + sign + "</span>");

or if you want to use regex it would be overcomplicated:

result = signs.map(sign => sign.replace(/(.+)/g, "<span class='some-class'>&nbsp;$1</span>"));
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