admin管理员组

文章数量:1336331

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.

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.

Share Improve this question edited Jun 15, 2011 at 10:03 Lightness Races in Orbit 385k77 gold badges666 silver badges1.1k bronze badges asked Jun 15, 2011 at 9:46 angry kiwiangry kiwi 11.5k28 gold badges123 silver badges167 bronze badges 4
  • only for the multiplication operator? – patapizza Commented Jun 15, 2011 at 9:48
  • 4 Where did these values e from? – Lightness Races in Orbit Commented Jun 15, 2011 at 9:48
  • @tomalak it es from yaml, which is a config file. – angry kiwi 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. – T.J. Crowder Commented Jun 15, 2011 at 9:57
Add a ment  | 

5 Answers 5

Reset to default 7

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 plex.

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 plex — other operators, spaces around the values, parentheses, etc.


Picking up on Andy E's ment 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...

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

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

var evaluated = eval(s);

alert(evaluated) will then alert 1000.

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

本文标签: javascriptConvert string to numberStack Overflow