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

278
Vistas
how to use an array to replace parts of a string

If I have an array of values ['123', '456', '789'] what approach can I use to iterate over this array and replace, in matching sequence, parts of a string that have the value :id (for example users/:id/games/:id/server/:id)?

At the moment, I've been toying around with a .forEach(), but the initial value isn't getting updated per iteration. Curious how the following example could be altered in a way that would allow me to pass in an updated version of the string with one less :id on it.

goal:

input: { target: 'users/:id/games/:id/server/:id', ids: ['123', '456', '789'] }

output: 'users/123/games/456/server/789'

const injectPathVariables = (
  target: string,
  ids: string[]
): string => {
  let newStr: string | undefined;
  ids.forEach(id => {
    if (newStr === undefined) {
      newStr = target.replace(':id', id);
      return;
    }
    newStr.replace(':id', id);
  });
  return newStr;
};
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

let string = "users/:id/games/:id/server/:id";
const arr = ["123", "456", "789"];
arr.forEach((i) => {
  string = string.replace(":id", i);
});

console.log(string);

Here it is in action.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Array.forEach() irritates the array.

Array.map() irritates the array and returns a new array.

const injectPathVariables = (
  target: string,
  ids: string[]
): string => {
  let newStr: string | undefined;
  ids.map(id => {
    if (newStr === undefined) {
      newStr = target.replace(':id', id);
      return; // this will result in replacing id with Undefined 
    }
    newStr.replace(':id', id);
  });
  return newStr;
};
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