0

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?

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for explaining it. That really helped me out :D
@Chris can you accept the answer and upvote if it helps you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.