function calc() {
let equation = document.getElementById('equation').value || 0;
let result = document.getElementById('result');
// Make sure you only have numbers, operators and parenthesis
let matches = equation.match(/[\d\+\-\/\*\(\)]/g);
if (matches && matches.length == equation.length) {
result.innerText = eval(equation);
} else {
result.innerText = "Error";
}
}
function calc() {
let equation = document.getElementById("equation").value || 0;
let result = document.getElementById("result");
// Make sure you only have numbers, operators and parenthesis
let matches = equation.match(/[\d\+\-\/\*\(\)]/g);
// Get a clean equation from allowed chars
let clean = matches.join("");
console.log(clean);
// Get the numbeers and operator separately
let operators = clean.split(/\d+/).filter((op) => op !== "");
let numbers = clean.split(/[\+\-\*\/]/).map(n=>parseInt(n));
console.log(operators, numbers);
// Start with the first number then calculate based on the operator
let temp = numbers[0];
operators.forEach(function (op, index) {
switch (op) {
case "+":
temp += numbers[index + 1];
break;
case "-":
temp -= numbers[index + 1];
break;
case "*":
temp = temp * numbers[index + 1];
break;
case "/":
temp = temp / numbers[index + 1];
break;
}
});
result.innerText = temp;
}