I am creating a calculator in which I get a string from an input field. That string could for example be 2+3*9/3-6
.
Now I want to perform multiplication and division operations first,
so I will get 2+ 9 -6
where 9
will be the answer of the higher precedence operations.
So far I have done this. It is a complete function:
function calculateResult(){
var higher = /(\d+[*\/]\d+)/g;
calstr = $('#input-display').val();
var m = '*';
var res = calstr.split(higher);
console.log(res.length+ ' : ' + res);
// console.log(res);
if(res.length > 2){
console.log('split success');
var index = 0;
do{
for(var i = 1; i < res.length; i+=2){
var a = res[i].split(/([0-9\.]+)/g);
console.log('before calculation : '+calstr);
var regex = RegExp('(?:.*?(\\d+[*\/]\\d+)){' + i + '}');
console.log('regex generated : '+regex);
if(a[2] == '*'){
calstr = calstr.replace(regex , Number(a[1])*Number(a[3]));
}
else if(a[2] == '/'){
calstr = calstr.replace(regex , Number(a[1])/Number(a[3]));
}
console.log('replaced result : ' + calstr);
console.log('replaced result at : ' + calstr.search(regex));
}
// console.log('result : ' + calstr);
console.log('multiplication complete');
res = calstr.split(higher);
console.log('result is : '+res);
}while(res.length > 2);
}
else if(res.length == 1)
console.log('split failed');
}
When I try to replace the result inside a string, the replace succeeds. But on some several inputs it replaces the entire string that was passed as argument to this function, which is not what I want.
What did I do wrong?
If still something is unclear, I am happy to give clarifications.
After multiplication and division runs smoothly, I plan to change these regular expressions, to add support for addition and subtraction. It would use the same code but with a next run for the lower precedence operators.