Reputation: 1654
I'm having a little trouble understanding the split function in JavaScript.
I'm trying to get the numbers before and after the operator in a sum.
My code is as follows:
else if(btnVal == '=') {
var equation = inputVal;
var lastChar = equation[equation.length - 1];
// Replace all instances of x with * respectively.
equation = equation.replace(/x/g, '*');
if (operators.indexOf(lastChar) > -1 || lastChar == ',')
equation = equation.replace(/.$/, '');
if (equation)
if (equation.indexOf('+') == 1) {
var firstNumber = equation.split('+')[0];
var secondNumber = equation.split('+')[1];
var result = Number(firstNumber) + Number(secondNumber);
input.innerHTML = result;
}
else if (equation.indexOf('*') == 1) {
firstNumber = equation.split('*')[0];
secondNumber = equation.split('*')[1];
result = Number(firstNumber) * Number(secondNumber);
input.innerHTML = result;
}
else if (equation.indexOf('-') == 1) {
firstNumber = equation.split('-')[0];
secondNumber = equation.split('-')[1];
result = Number(firstNumber) - Number(secondNumber);
input.innerHTML = result;
}
else if (equation.indexOf('/') == 1) {
firstNumber = equation.split('/')[0];
secondNumber = equation.split('/')[1];
result = Number(firstNumber) / Number(secondNumber);
input.innerHTML = result;
}
decimalAdded = false;
}
This all works just fine when I use 1 number, e.g. 1 + 1, but won't work with 77 + 8.
Could someone help me out on this one so that this also works with two numbers?
Upvotes: 0
Views: 68
Reputation: 1258
Below condition is wrong in case of input "77 + 1"
equation.indexOf('+') == 1
in above case indexOf '+' will be 2 instead of 1
change that line and for other operators as well like below
equation.indexOf('+') != -1
Upvotes: 4