开发者

Convert string to number

开发者 https://www.devze.com 2023-03-13 14:49 出处:网络
I hav开发者_如何学编程e some simple variables whose values are numeric strings: var s = \'10*10*10\',

I hav开发者_如何学编程e 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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消