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

275
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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