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 values from a string if they are present in an array of variables

Having the following array of objects:

const variables = [
                   {name: '%NAME%', value: 'joe'},
                   {name: '%EMAIL%', value: '%NAME%@mail.com'},
                   {name: '%HOBBY%', value: 'tennis'}
                  ];

And the input string:

const inputString = `Hi, my name is %NAME%', I like %HOBBY%, you can contact me at %EMAIL%`;

The function should take as arguments variables and inputString and return the following sting:

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

'Hi, my name is joe, I like tennis, you can contact me at joe@mail.com'

Here is the function so far:

function doMagic(variables, inputString) {
  let output = inputString;
  for (let i = 0; i < variables.length; i++) {
     output = inputString.replace(variables[i].name, variables[i].value);
  }
  return output;
}

Unfortunatelly, this only finds one occurrence, in case there are more, and it doesn’t go into nested variables, like %EMAIL%.

Any ideas to improve?

>Solution :

We can do a regex replacement with the help of a callback function:

var variables = [
                   {name: '%NAME%', value: 'joe'},
                   {name: '%EMAIL%', value: 'joe@mail.com'},
                   {name: '%HOBBY%', value: 'tennis'}
                  ];
var regex = new RegExp("(" + variables.map(x => x.name).join("|") + ")", "g");
var inputString = "Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%";
var output = inputString.replace(regex, (m) => {
    return variables.filter(x => x.name == m)[0].value;
});
console.log(output);

The strategy here is to first build a regex alternation of names from the map. We do a global regex search for these names in the input string. For each match, the callback function replaces the name with the value from the map.

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