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

191
Visualizações
Replace part of string with new value for each time it appears in string, JavaScript

I want to replace ":player:" from my string with a player-name from localStorage. And if there are multiple ":player:" in the string do I want to replace ":player:" with a different name for each time it comes up in the string so for example.

Lets say that I have a string that looks something like this:

str = ":player: drink 5 sips if :player: has 5 fingers"

Then I want the output to be able to be.

str = "Alex drink 5 sips if Harry has 5 fingers"

My localStorage data looks like this: namesArray = [["Alex",0],["Harry",1]]

I have tried different variants of str.replace() but it's not working the way that I want it to...

Does it exist something like this?

forEach(str.includes(":player:") => {
  str.replace(":player:", localStorageName[randomNumber].name);
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use the replaceAll() method with a function as the replacement. It can then retrieve from localStorage and increment the index each time it's called.

localStorage.setItem('name', JSON.stringify(['Alex', 'Harry']));
let str = ":player: drink 5 sips if :player: has 5 fingers";
let index = 0;
str = str.replaceAll(':player:', () => JSON.parse(localStorage.getItem('name'))[index++]);
console.log(str);
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