Reputation: 325
I am doing this for a calculator project, I want to check if the operation is valid or not, somehow I cannot check for the Boolean value of eval
if it is false
? on the console:
Boolean(eval('2+2(9.1-)9'));
Boolean(2+2(9.1-)9); // Both operations return unexpected token
unlike Boolean(2+2)
<-- returns true
. Help?
Upvotes: 3
Views: 123
Reputation: 7151
You actually don't need to evaluate the code in order to see if it's valid - just try
creating a Function
:
function checkIt() {
var fn
try {
var fn = new Function(document.getElementById("code").value)
alert("Great, that's a valid piece of code!")
} catch (e) {
alert("That's not a valid piece of code.")
}
}
<input id="code">
<button onclick="checkIt()">Check it</button>
For example, try "123", "valid", and "''not[valid!!!".
Though if you are going to be evaluating it right away, if it's valid, you should probably just check if the error is a syntax error, or otherwise.
function doIt() {
var fn
try {
var result = eval(document.getElementById("code").value)
alert("The result is: " + result)
} catch (e) {
if (e instanceof SyntaxError) {
alert("That's not a valid piece of code.")
} else {
alert(e.message)
}
}
}
<input id="code">
<button onclick="doIt()">Check it</button>
For example, try the same things you tried before and see how this behaves.
Upvotes: 1
Reputation: 4027
If I understood your question correctly, the only thing you want to know is "Is that a valid expression". One very simple way to check this is using eval()
as you did here, and to enclose it in a try
, and see if any error occurs. For example, you could write this :
try {
eval('2+2(9.1-)9');
valid = true;
} catch (e) {
valid = false;
}
Then, the variable valid
contains true
if the expression is valid, and false
if it is not.
Warning with eval()
though : Every valid code will pass this test, not only mathematical expressions : Plus, that code will be executed. Be careful what strings you give it.
Upvotes: 0