Bhaumik Joshi
Bhaumik Joshi

Reputation: 233

How to pass arguments to strings in eval() javascript?

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>.

Upvotes: 1

Views: 183

Answers (2)

TopW3
TopW3

Reputation: 1527

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}")

Upvotes: 1

Yousername
Yousername

Reputation: 1012

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)});

Upvotes: 0

Related Questions