Let's work with an array of objects:
const data = [
{ key: '%KEY1%', value: 'value1' },
{ key: '%KEY2%', value: '%KEY1% abc' },
{ key: '%KEY3%', value: 'xyz' }
];
Now, we have a string to process:
const inputText = `This is %KEY1%, also known as %KEY2%. Contact us at %KEY3%`;
The goal is to create a function that accepts data
and inputText
, and outputs the modified string:
'This is value1, also known as value1 abc. Contact us at xyz'
Here is the current implementation:
function processData(data, inputText) {
let result = inputText;
for (let index = 0; index < data.length; index++) {
result = inputText.replace(data[index].key, data[index].value);
}
return result;
}
Unfortunately, this approach only replaces one occurrence and doesn't handle nested variables, like %KEY2%
.
How would you enhance this functionality?