script function calculate str var was_str var sum_or_diff function sub

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<script>
function calculate(str) {
var was_str;
var sum_or_diff=function(sub, a, sign, b) {
return sign=="-" ? a-b : +a + +b;
};
var mult_or_div= function(sub, a, sign, b) {
return sign=="*" ? a*b : a/b;
};
var power= function(sub, a, b) {
return Math.pow(a, b);
};
var match_power= /(-?[\d\.]+)\s*\^\s*(-?[\d\.]+)/g;
var match_mult_div= /(-?[\d\.]+)\s*([\*\/])\s*(-?[\d\.]+)/g;
var match_sum_diff= /(-?[\d\.]+)\s*([\+-])\s*(-?[\d\.]+)/g;
var get_value= function(sub, exp) {
while(exp.indexOf("^")!==-1)
exp= exp.replace(match_power, power);
while(match_mult_div.test(exp))
exp= exp.replace(match_mult_div, mult_or_div);
while(match_sum_diff.test(exp))
exp= exp.replace(match_sum_diff, sum_or_diff);
return exp;
};
while(str.indexOf("(") !== -1)
str=str.replace(/\(([^\(\)]*)\)/g, get_value);
return get_value("", str);
};
function calcul(){
var inform = document.getElementById("value1").value;
inform = calculate(inform);
document.getElementById("value2").value=inform;
return 0;
}
</script>
<form action="" id="nothing">
<input type="text" id="value1" value="Тут вводить выражение">
<input type="text" id="value2" value="Тут будет ответ">
<input type="button" value="Подсчет" id="but" onclick="calcul()" />
</form>