0

I currently have a template read from a file into tstr and I replace placeholders in it like so:

const obj = { main: 3 };
const func = () => { const a = 2; };

let tstr = `

<fname func>

<fbare func>

<var obj.main>

`;

tstr = tstr.replace(/<var ([^>]+)>/g, function () { return eval(arguments[1]) });
tstr = tstr.replace(/<fbare ([^>]+)>/g, function () { return eval(arguments[1]).toString() });
tstr = tstr.replace(/<fname ([^>]+)>/g, function () { return arguments[1] + ' = ' + eval(arguments[1]).toString()  });


console.log(tstr);

Is there a simple way to rewrite these replacements without eval?

BTSM
  • 1,585
  • 8
  • 12
  • 26
  • Have you seen: ["Variable" variables in JavaScript](https://stackoverflow.com/q/5187530) and [Accessing nested JavaScript objects and arrays by string path](https://stackoverflow.com/a/6491621)? Combining these should help remove the `eval()` calls – Nick Parsons May 26 '22 at 09:00
  • There is a lot of hairy code there, combining it (and I wouldn't know how) doesn't seem to fall into the "simple" category (for me). I was looking more into few (one) line solution. – user9163823 May 26 '22 at 11:41
  • The main thing that makes this complex is `obj.main`. Handling `func` in th "variable variables" link is fairely minimal as it just adds an object. There isn't a native way to deal with `"obj.main"` as its a string, so you'll need to define your own function to parse and handle that. There are simpler ways to deal with just dot-notation, but you can have all sorts of different combinations if you want to allow normal object access `obj['main'].foo.bar['baz']`, etc... so it gets complex dealing with that. That's usually why people use a templating engine for something like this. – Nick Parsons May 26 '22 at 11:58

0 Answers0