Evaluating a string as a mathematical expression in JavaScript
I've eventually gone for this solution, which works for summing positive and negative integers (and with a little modification to the regex will work for decimals too):
function sum(string) {
return (string.match(/^(-?\d+)(\+-?\d+)*$/)) ? string.split('+').stringSum() : NaN;
}
Array.prototype.stringSum = function() {
var sum = 0;
for(var k=0, kl=this.length;k<kl;k++)
{
sum += +this[k];
}
return sum;
}
I'm not sure if it's faster than eval(), but as I have to carry out the operation lots of times I'm far more comfortable runing this script than creating loads of instances of the javascript compiler
How to evaluate a math expression given in string form?
With JDK1.6, you can use the built-in Javascript engine.
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class Test {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "40+2";
System.out.println(engine.eval(foo));
}
}
Safe evaluation of arithmetic expressions in Javascript
You can try JavaScript Expression Evaluator:
This library is a modified version of
Raphael Graf’s ActionScript Expression
Parser. When I wrote the JavaScript
Function Plotter, I wanted a better
alternative to using JavaScript’s eval
function. There’s no security risk
currently, because you can only run
code in your own browser, but it’s not
as convenient for math (Math.pow(2^x)
instead of 2^x, etc.).
Then your code will be like that:
console.info ( Parser.evaluate( "2 * (3 + 4)" ) ); //prints 14
The source code is on GitHub and it's published on npm as expr-eval
. Can be used like so:
import { Parser } from 'expr-eval';
console.log(Parser.evaluate("2 * (3 + 4)")); // 14
Is there a way to evaluate strings as mathematical expressions in HTML/JS?
The function you're in need of is eval()
.
eval('1+1');
// Output: 2
Or implemented in your code that would be:
var equation = document.getElementById("equation").value;
var answer = document.getElementById("answer");
answer.innerHTML = eval(equation);
For more on the eval()
function, read the documentation.
Check if string is a mathematical expression in JavaScript
Here's a regex that can do what I think you're looking for:
/(?:(?:^|[-+_*/])(?:\s*-?\d+(\.\d+)?(?:[eE][+-]?\d+)?\s*))+$/
https://regex101.com/r/w74GSk/4
It matches a number, optionally negative, with an optional decimal number followed by zero or more operator/number pairs.
It also allows for whitespace between numbers and operators.
const re = /(?:(?:^|[-+_*/])(?:\s*-?\d+(\.\d+)?(?:[eE][+-]?\d+)?\s*))+$/;
function test(s) {
console.log("%s is valid? %s", s, re.test(s));
}
// valid
test(" 1 ");
test("1 + 2");
test(" 1 * 2 * 3 ");
test("-1 * 2 - -3");
test("-1 * 2 - -3e4");
test("-1 * 2 - -3.5E6");
// invalid
test("1 +");
test("1 + foo");
Js - Alternatives to eval mathematical expression with operator as string
implement functions for operators
ops = {
'>': (a, b) => a > b,
'>=': (a, b) => a >= b
};ops[expressionObject.operator](object[property], expressionObject.number)
if the expression is always valid as expected. then following should faster as no parsing.
eval(
${object[property]}${expression}
)
Evaluating a string as a mathematical expression in JavaScript
I've eventually gone for this solution, which works for summing positive and negative integers (and with a little modification to the regex will work for decimals too):
function sum(string) {
return (string.match(/^(-?\d+)(\+-?\d+)*$/)) ? string.split('+').stringSum() : NaN;
}
Array.prototype.stringSum = function() {
var sum = 0;
for(var k=0, kl=this.length;k<kl;k++)
{
sum += +this[k];
}
return sum;
}
I'm not sure if it's faster than eval(), but as I have to carry out the operation lots of times I'm far more comfortable runing this script than creating loads of instances of the javascript compiler
Related Topics
How to Invoke a Jsf Managed Bean on a HTML Dom Event Using Native JavaScript
JavaScript: Difference Between .Foreach() and .Map()
Check If a Value Is an Object in JavaScript
What's the Right Way to Decode a String That Has Special HTML Entities in It
Load Less.Js Rules Dynamically
What Is the Best Method to Reduce the Size of My JavaScript and CSS Files
Preventing Child from Firing Parent's Click Event
Npm Not Installing Returns Error Consistently
Mocha/Chai Expect.To.Throw Not Catching Thrown Errors
Chained Promises Not Passing on Rejection
How to Parse a CSV String With JavaScript, Which Contains Comma in Data
JavaScript Add Leading Zeroes to Date
What Is the JavaScript ≫≫≫ Operator and How to Use It
Check Browser CSS Property Support with JavaScript
Webkit-Transform Overwrites Z-Index Ordering in Chrome 13