How do I parse and evaluate a mathematical expression in a string (e.g. \'1+1\'
) without invoking eval(string)
to yield its numerical value?
You can do + or - easily:
function addbits(s) {
var total = 0,
s = s.match(/[+\-]*(\.\d+|\d+(\.\d+)?)/g) || [];
while (s.length) {
total += parseFloat(s.shift());
}
return total;
}
var string = '1+23+4+5-30';
console.log(
addbits(string)
)
More complicated math makes eval more attractive- and certainly simpler to write.