S
S
Slava Nehria2015-10-29 17:51:20
JavaScript
Slava Nehria, 2015-10-29 17:51:20

How to convert string with mathematical expression?

Okay, the bottom line is this: there is an array. It contains, for example, the following lines: "1 + 1 = 2", "2 - 1 = 5", "4 * 4 = 16". And it would be necessary to somehow compare the string with true / false. If you take and stupidly compare, then it produces false, regardless of whether the expression is correct, but this is predictable. How to solve my problem? Thank you. And sorry for the noobness, I just recently took up JS.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Zuev, 2015-10-29
@yurzui

function runTest(str) {
  var args = str.split('=');
  return (new Function('', 'return ' + args[0] + '===' + args[1] +';'))();
}

runTest('4 * 4 = 16');  //true

D
Dmitry Kovalsky, 2015-10-29
@dmitryKovalskiy

Try to split the string through = and pass the resulting 2 pieces to the eval function. And compare the results

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question