for example:
var s = '3+3';
s.replace(/([\d.]+)([\+\-)([^,]*)/g,
function(all, n1, operator, n2) {
r = new Number(n1) ??? new Number(n2);
return r;
}
);
note: not using eval()
for example:
var s = '3+3';
s.replace(/([\d.]+)([\+\-)([^,]*)/g,
function(all, n1, operator, n2) {
r = new Number(n1) ??? new Number(n2);
return r;
}
);
note: not using eval()
Are Variable Operators Possible?
Not possible out of the box, but he gives a nice implementation to do it, as follows. Code by delnan.
var operators = {
'+': function(a, b) { return a + b },
'<': function(a, b) { return a < b },
// ...
};
var op = '+';
alert(operators[op](10, 20));
So for your implementation
r = operators[operator](new Number(n1), new Number(n2));
Your regex is a bit broken.
/([\d.]+)([\+\-)([^,]*)/g
should probably be
/([\d.]+)([+-])([\d+]+)/g
then you can switch on the operator:
function (_, a, op, b) {
switch (op) {
case '+': return a - -b;
case '-': return a - b;
}
}
s.replace(/(\d+)\s*([+-])\s*(\d+)/g, function(all, s1, op, s2) {
var n1 = Number(s1), n2 = Number(s2);
return (op=='+') ? (n1+n2) : (n1-n2);
});