0

I have a string like '${abc}' from server.

I want change it to a placeholder string.

function handle(stringFromServer) {
    // stringFromServer='${abc}'
    const abc = '1';
    // do sth to change it to `${abc}`
    console.log(stringFromServer); // I want it print 1 
}

Is there more elegant way other than parse it by regex and then call eval function?

HJWAJ
  • 170
  • 2
  • 10
  • 2
    I’d probably start with an object that holds your values as key–value pairs, then match all `${`…`}` occurrences and replace them by looking up the key in the object, e.g. `const values = { abc: "1" }; return stringFromServer.replaceAll(/\$\{(.*?)\}/gsu, (_all, key) => values[key]);`. But this only works for simple keys; more complex expressions need a more elaborate solution. – Sebastian Simon Oct 17 '22 at 09:26

0 Answers0