Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace String with Multiple Arrays 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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading