I have some simple variables whose values are numeric strings:
var s = '10*10*10', v = '60*10'; I want to turn s into 1000 and v to 600.
Use eval() function:
var result = eval('10*10*10'); alert(result); // alerts 1000 If the strings are from a truly trusted source, you can use eval to do that:
var s = '10*10*10'; var result = eval(s); But note that eval fires up a JavaScript parser, parses the given string, and executes it. If there's any chance that the given string may not be from a trusted source, you don't want to use it, as you're giving the source the ability to arbitrarily execute code.
If you can't trust the source, then you'll have to parse the string yourself. Your specific examples are easy, but I'm sure your actual need is more complex.
The dead easy bit:
var s, operands, result, index; s = '10*10*10'; operands = s.split('*'); result = parseInt(operands[0], 10); for (index = 1; index < operands.length; ++index) { result *= parseInt(operands[index], 10); } ...but again, I'm sure your actual requirement is more complex — other operators, spaces around the values, parentheses, etc.
Picking up on Andy E's comment below, whitelisting might well be a way to go:
function doTheMath(s) { if (!/^[0-9.+\-*\/%() ]+$/.test(s)) { throw "Invalid input"; } return eval('(' + s + ')'); } var result = doTheMath('10*10*10'); // 1000 var result2 = doTheMath('myEvilFunctionCall();'); // Throws exception That regexp may not be perfect, I'd stare at it long and hard before I'd let any unwashed input head its way...
eval where appropriate, warnings of when it isn't, and an alternative (that I was thinking of posting, but cba to come up with.. whew what effort!)doTheMath version just to be <s>paranoid</s> cautious. But a raw eval would be totally fine in that case as well, I'd think.this could be achieved quite simply without resorting to eval
function calc(s) { s = s.replace(/(\d+)([*/])(\d+)/g, function() { switch(arguments[2]) { case '*': return arguments[1] * arguments[3]; case '/': return arguments[1] / arguments[3]; } }) s = s.replace(/(\d+)([+-])(\d+)/g, function() { switch(arguments[2]) { case '+': return parseInt(arguments[1]) + parseInt(arguments[3]); case '-': return arguments[1] - arguments[3]; } }) return parseInt(s); } alert(calc("10+5*4"))
evalis fine.