简体   繁体   中英

JavaScript function to add a string of numbers

Not sure how to word this and so am not having much luck in Google searches...

I need to calculate a value for a string of numbers.

Example. A user types in "1.00 + 2.00 - 0.50" into a text field. The function should be able to take that string and calculate the result to return $2.50.

Anyone have a way to do this in their bag of tricks?

如果实际上是数学运算,则可以使用eval,但不确定那是您想要的:

document.write(eval("1.00 + 2.00 - 0.50"));

Theo T的答案似乎是最简单的方法,但是如果您需要编写自己的简单解析器,则可以从拆分字符串开始,然后在输出中寻找运算符。

Just to improve Theo's answer.

You should NOT be using eval unless you're absolutely sure what you are passing to that function. Since eval will run the code, you can write any JavaScript code and it will be executed.

One of the ways of making sure you will only get the right code is using the following script:

var str = "$34.00 + $25.00 alert('some code')"; // Our string with code
var pattern = /[0-9\+\-\.\*\/]*/g; // Regex pattern
var math_operation = str.match(pattern).join(''); // Getting the operation
document.write(eval(math_operation));​ // Getting the result

This not only allows the user to type things like $34.00 + $5.00 but also prevents from code being injected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM