I'm making home page using AngularJS and there is arithmetic function.
<div class="input-form">
<input ng-model="value1" id="value1" type="number" />
<input ng-model="value2" id="value2" type="number" />
<input ng-model="value3" id="value3" type="number" />
<input ng-model="value4" id="value4" type="number" />
<input ng-model="value5" id="value5" type="number" />
</div>
<div class="equation-form">
<input ng-model="equation" type="text" />
</div>
<button class="yellow" ng-click="calculate()">Calculation</button>
If user press "Calculation" button after input arithmetic equation to equation field, need to calculate result and send server.
Equation input like as "1 + 2 - 3 * 4 + 5"
.
1,2,3,4,5 values means input value named as value1, value2, value3, value4, value5
Here is what I tried to achieve the calculation:
scope.calculate = function () {
let equation = scope.equation.replace(/s+/g, ''); // remove spaces
if (!/^d+(?:[+-]d+)*$/.test(expression)) { //
console.error('wrong equation');
return;
}
let fieldIndexes = expression.split(/(?=[+-])/); // split expression
if (fieldIndexes) {
fieldIndexes.forEach(x => {
// process calculation
});
}
}
Function is done in two steps:
First, split equation to [ 1, +2, -3, *4, 5 ].
Second, calculate splited equation.
But now, I've only split by "-", "+".
If user input "1 + 2 - 3 + 4 - 5"
, current function split it to "1", "+2", "-3", "+4", "-5"
.
How can I split string by "-", "+", "*", "/" symbol?
Any suggestions?