1

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.

4
  • only for the multiplication operator? Commented Jun 15, 2011 at 9:48
  • 4
    Where did these values come from? Commented Jun 15, 2011 at 9:48
  • @tomalak it comes from yaml, which is a config file. Commented Jun 15, 2011 at 9:55
  • 1
    If you trust the contents of the config file not to contain malicious script code where you're expecting these values, eval is fine. Commented Jun 15, 2011 at 9:57

5 Answers 5

7

Use eval() function:

var result = eval('10*10*10'); alert(result); // alerts 1000 
Sign up to request clarification or add additional context in comments.

1 Comment

Yes but I can't upvote this answer as you do not qualify it with any warnings about when this would be an incredibly bad idea.
7

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 

Live example

That regexp may not be perfect, I'd stare at it long and hard before I'd let any unwashed input head its way...

5 Comments

+1; it might be easiest to whitelist only numbers and mathematical operators in the input, using a regex.
@Andy E: Yeah, that could be a way to go if you semi-trust the source. :-)
+1 Great answer. Use of 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!)
hey I would mark this as answer if inputs come from arbitrary sources. In case, the values come from a config file in the server. I'm doing js server-side not client so I guess my config file is safe :)
@runrunforest: I think I would typically trust my config files, but since you're parsing config entries which I assume you do once at startup, I'd probably use the 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.
1

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")) 

Comments

0

You can use the eval function to evaluate an expression in a string:

var evaluated = eval(s);

alert(evaluated) will then alert 1000.

Comments

0

If you "just" want to have these numbers out of the string you can do

eval(s) 

to get "10*10*10" as a Number

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.