[英]How to pass arguments to strings in eval() javascript?
Let we have the user input stored in a variable t,让我们将用户输入存储在变量 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 作为,
t = '[1,2,3,4].map(e=>"<div> e </div>")'
. 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.所以现在出现的问题是如何将此字符串传递给
eval
以便它认为它是一个参数变量而不是字符串。 So, the output becomes,所以,输出变成,
<div>1</div><div>2</div><div>3</div><div>4</div>
. <div>1</div><div>2</div><div>3</div><div>4</div>
。
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}")
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)});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.