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

120
Visualizações
Replace string with multiple array value

I have 2 Arrays where the first Array is for the key, and the second Array for the values.

var getKeys = Object.keys(data); // ['[name]', '[address]', '[gender]']
var getValues = Object.values(data); // ['Franky', 'Lemon Street', 'Male']

and I have a string like this :

'My name is [name]. I live at [address]. My gender is [gender].'

I want to replace the keys above with Array values like this :

'My name is Franky. I live at Lemon Street. My gender is Male.'

I have tried using map like this :

getKeys.map((key) => {
    getValues.map((value) => {
        const replaceValue = dataValue.replace(key, value);
        console.log(replaceValue)
    });
});

But only the last value replaced. How to replace for all keys?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

There are logical issues in your code. You dont have to map though both arrays. Instead, loop through getKeys array, replace the keys from getKeys array with values from getValues array.

Why only last value is replaced?

You are declaring const replaceValue inside the map function. This will generate new memory for replaceValue whenever the loop executes. So each execution creates a new variable and only the last variable will be displayed in the output.

Working Fiddle

var getKeys = ['[name]', '[address]', '[gender]'];
var getValues = ['Franky', 'Lemon Street', 'Male'];
const myStr = 'My name is [name]. I live at [address]. My gender is [gender].';
let replaceValue = myStr;
getKeys.forEach((key, index) => {
    replaceValue = replaceValue.replace(key, getValues[index]);
});
console.log(replaceValue);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use an extensible approach and try to avoid replace which can create confusion and buggy code for the large text. The simple approach will be to have an associative kind of array with the template literal. I believe you have a data object, you can simply modify the below snippet.

Below is one example.

var getKeys = ['name', 'address', 'gender'];

var getValues = ['Franky', 'Lemon Street', 'Male']

var obj = {};
for(var i = 0; i < getKeys.length; i++) {
    obj[getKeys[i]] = getValues[i];
}

var str = `My name is ${obj['name']}. I live at ${obj['address']}. My gender is 
${obj['gender']}.`;

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