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

185
Vistas
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 Respuestas
Responde la pregunta

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