1

Let we have the user input stored in a variable t,

let t = '[1,2,3,4].map(e=>"<div>{{ e }}</div>")';.

Whereby a user is forced to write this syntax to execute, so on

t = t.replace(/\{\{(.*)?\}\}/g,"$1");.

We will be getting new t as,

t = '[1,2,3,4].map(e=>"<div> e </div>")'.

So now the question arises is how to pass this string to eval so that it considers it as an argument variable not the String. So, the output becomes,

<div>1</div><div>2</div><div>3</div><div>4</div>.

2
  • 1
    t = '[1,2,3,4].map(e=>"<div>" +e +" </div>")'. otherwise it is considerd as a string "+e +" Commented Dec 26, 2019 at 19:58
  • I wouldn't suggest using eval() for anything. You're opening yourself up to security risks. See the MDN docs developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…! Commented Dec 26, 2019 at 20:46

2 Answers 2

1

The answer would not be the same depending on the user input. In the current case, this code would work.

t = '[1,2,3,4].map(e=>`<div> ${e} </div>`)'

you can get this string from the original as follows.

t = t.replace(/"/g, '`').replace(/\{\{(.*)?\}\}/g, "${$1}")

Sign up to request clarification or add additional context in comments.

1 Comment

If I use template literals, and pass the variables to it. Then what about the Internet Explorer
0

This would work:

let t = '[1,2,3,4].map(e=>"<div>{{"+e+"}}</div>")';

t = t.replace(/\{\{(.*)?\}\}/g,"$1");

t = eval(t);

t.forEach(v => {document.write(v)});

1 Comment

It's a user input, they are not supposed to put plus sign in the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.