Reputation: 1981
The question is as simple as the title: How do I make sure a string contains a calculation.
I have a string which should contain a calculation. The string could be something like this: "10 * 10 / 2 * 3"
. But there are always people who want to break things, so I want to check if it's a calculation. The user could fill in something like this: "alert('hi!')"
.
When I use eval()
, it will still alert the user (if the user filled in: "alert()"
).
Does anyone know how I can check if the string contains a calculation and nothing else?
Upvotes: 1
Views: 980
Reputation: 4696
You could just check the input sting for characters. If the sting contains any characters like (a,b,c ... z) then you do not eval it.
Upvotes: 0
Reputation: 23863
In this case, I'd recommend a different solution.
Rather than trying to white list
your string to ensure it is just math expressions, I'd recommend you try to use library specifically for handling math in the first place.
I have no experience with it, but a quick google of "javascript math parsers" brought me to this one: http://mathjs.org/docs/expressions/parsing.html
Upvotes: 1
Reputation: 17721
If you just want to check if a string contains an arithmetic operation, you coul match it with a regexp like this:
([-+]?[0-9]*\.?[0-9]+[\/\+\-\*])+([-+]?[0-9]*\.?[0-9]+)
BUT, i strongly suggest to use a javascript library as mathjs, or the JavaScript Expression Evaluator library, with which you can do, for example:
Parser.evaluate("3 ^ x", { x: 7 });
These libraries will take care to ignore code injection, for sure... :-)
Upvotes: 3