最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Convert variable string value to expression in JavaScript - Stack Overflow

programmeradmin2浏览0评论

i am trying to convert a string value to expression so that i can use it in if condition like:

var StringVal = '20 > 18 && "yes" == "yes"';

if(StringVal){

    ....
}

is it possible to do this, please suggest me.

Thanks

i am trying to convert a string value to expression so that i can use it in if condition like:

var StringVal = '20 > 18 && "yes" == "yes"';

if(StringVal){

    ....
}

is it possible to do this, please suggest me.

Thanks

Share edited Sep 10, 2016 at 13:20 Xotic750 23.5k8 gold badges59 silver badges81 bronze badges asked Sep 10, 2016 at 13:01 Rahul SharmaRahul Sharma 6221 gold badge7 silver badges25 bronze badges 10
  • eval would do it, or most likely the Function equivalent. – Xotic750 Commented Sep 10, 2016 at 13:04
  • yes..but it will not work for "yes" == "yes" – Rahul Sharma Commented Sep 10, 2016 at 13:05
  • 1 Why do you need to do this? – Xotic750 Commented Sep 10, 2016 at 13:06
  • i am working on some survey app and from web service i am getting: [[abc]] > 18 && [[xyz]] == "yes" [[abc]] and [[xyz]] stands from previous questions answer and i just replace that [[..]] string to real values and after that i have to check the condition.. – Rahul Sharma Commented Sep 10, 2016 at 13:10
  • i think eval is working... – Rahul Sharma Commented Sep 10, 2016 at 13:10
 |  Show 5 more ments

3 Answers 3

Reset to default 7

It's not generally safe to take input from a user source and evaluate it, but you could use Function evaluation, or eval

var StringVal = '20 > 18 && "yes" == "yes"';
if (new Function('return (' + StringVal + ')')()) {
  console.log('ok');
}

Are eval() and new Function() the same thing?

Update: If you could give further information in your question as to why you feel this is necessary along with an example of your actual code, then a safer solution could be suggested.

Further: In JSON2, eval is used in JSON.parse

https://github./douglascrockford/JSON-js/blob/master/json2.js#L491

but you will also notice that some sanitising is performed before eval is called.

You can use function eval()

try this:

var StringVal = '20 > 18 && "yes" == "yes"';

if(eval(StringVal)){

    ....
}

other example:

var a = '1==3'
var b = '1==1'

console.log(eval(a));
// false
console.log(eval(b));
// true

Note that eval won't directly parse your text as an expression, e.g.

eval('{}'); // undefined

That's because {} is parsed as a block, not as an object initializer expression.

There are several ways to force it to be parsed as an expression, like nesting inside parentheses, or via a return statement. So I would use

function evalExpr(expr) {
  Function("return " + expr + ";");
  return eval("(" + expr + ")");
}
console.log(evalExpr('{}')); // Object {}
try { evalExpr('1),(2') } catch(err) { console.error(err); } // SyntaxError
try { evalExpr('1;2') } catch(err) { console.error(err); } // SyntaxError

eval("(" + expr + ")") evaluates as an expression, and previously Function("return " + expr + ";") checks that the expression does not contain an invalid ) to escape the wrapping parentheses.

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>