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

222
Visualizações
Chain replace for the same character appearing multiple times

Let's say I have a string like so

Danny is ? James is ? Allen is ?

And I want to replace it to

Danny is great James is wonderful Allen is magnificent

How can I use replace to do it?

I'm attempting to do something like

string.replace(/\?/g, 'great ').replace(/\?/g, 'wonderful ').replace(/\?/g, 'magnificent');

but I just get:

Danny is great James is great Allen is great

If the case was something like:

Danny is ? James is # Allen is $

string.replace(/\?/g, 'great ').replace(/\#/g, 'wonderful ').replace(/\$/g, 'magnificent');

It would work as expected, but since it's the same character it's not working.

Is there a neater way to achieve this than doing something like below?

string = string.replace(/\?/g, 'great ') 
string = string.replace(/\?/g, 'wonderful ')
string = string.replace(/\?/g, 'magnificent');
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are using the replace function with a regular expression with the /g (meaning: "global") option, which means it will replace the '?' everywhere in the string.

To replace only one occurence of '?' at a time, just use a normal string to find, eg: string.replace('?', 'great')

So, your full example would be:

string = string.replace('?', 'great ') 
string = string.replace('?', 'wonderful ')
string = string.replace('?', 'magnificent');
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