我有一个URL,我在哈希之后解析。哈希之后的内容是一个数学方程式(例如http://example.com/something#5+1),我想找到它的总和(或任何其他方程的结果,如产品,除法等)
我可以使用以下方法检索数字:
var url = (window.location.hash).substr(1) // returns "5+1" as a string
虽然我发现如果我尝试将其转换为数字,但实际上并没有进行数学计算。它将其减少到5,而不是显示8的总和。
这种转换可能吗?
谢谢!
答案 0 :(得分:6)
请勿eval()
来自网址的任意代码,因为它可以很容易地被用于XSS。我创建了一个名为JSandbox的库,它可以对JavaScript代码执行进行沙箱化,但它需要对Web worker的支持。对IE使用假工作者支持不是一个好主意,因为沙盒的安全性已经消失。
您的代码如下:
JSandbox.eval("with(Math){" + location.hash.substr(1) + "}", function (res) {
// handle the results here
});
使用它来处理错误:
JSandbox.eval("with(Math){" + location.hash.substr(1) + "}", function (res) {
// handle the results here
}, null, function (err) {
// handle errors here
});
我包含了一个with (Math) { ... }
包装器,因此哈希代码可以很快访问Math函数。 (例如。abs(..)
代替Math.abs(..)
)
答案 1 :(得分:1)
eval()
是执行计算的最简单方法,但您肯定想要验证您的输入是否合理:
var input = window.location.hash.substr(1);
var result = null;
try {
// Make sure the input is only numbers and supported operators.
if (/^[-+*/.()0-9]+$/.test(input))
result = eval(input);
} catch (ex) {
// Insert error handling here...
}
这个正则表达式应该过滤掉任何危险的输入。
答案 2 :(得分:1)
要真正做到这一点,您需要为数学表达式语言编写一个简单的解析器。据说这不是很难,但我自己从来没有做过。这是让javascript正确评估和解释数学表达式的唯一方法,而不是打开pandoras框,让所有类型的讨厌的东西通过简单(和愚蠢)调用eval()来实现。
或者您可以稍微浏览一下并找到已经完成此操作的人,例如:
答案 3 :(得分:0)
要执行字符串,请参阅eval,有些不这样做的原因在why-is-using-javascript-eval-function-a-bad-idea。
这意味着在任何重要性的代码中 - 来自不受信任的来源(例如互联网)的数据 - 你应该解析数字和数学运算......而不接受任何其他类型的输入。
答案 4 :(得分:0)
var code = "5+1";
var result = window.eval(code);
但是在所有具有eval的语言中,要小心你的评价。
答案 5 :(得分:0)
function CalculateString(hash) {
var ReturnValue;
var patt = '([\d*+-/.%])';
ReturnValue = hash.match(patt)[1];
ReturnValue = eval(ReturnValue);
if (ReturnValue > 0) {
return parseInt(ReturnValue,10);
} else {
return 0;
}
}
所以你可以这样做:
var Hash = (window.location.hash).substr(1);
var Calculation = CalculateString(Hash); // Retinerer result of the calculation if it is valid, otherwise it will give you 0.