0

I want to have a program that turns "-" into an actual minus sign the computer will recognize. Here is my code:

document.getElementById("answer").innerHTML = (Number(input.substr(Number(input.indexOf("+"))).slice(1)) + Number(input.substr(0, Number(input.indexOf("+")))));
aaaaa
  • 63
  • 1
  • 7

1 Answers1

1

I take it you're trying to build a calculator. I'd personally create different functions for adding, subtracting, etc. You could use eval(), but that's prone to XSS.

Here's a simple calculator showcasing the minus pre-built into the JavaScript calculation, so that you don't have to worry about extracting it from the input:

function add() {
  document.getElementById('answer').innerHTML = Number(document.getElementById('input1').value) + Number(document.getElementById('input2').value);
}

function subtract() {
  document.getElementById('answer').innerHTML = document.getElementById('input1').value - document.getElementById('input2').value;
}
<input id="input1">
<input id="input2">
<button onclick="add()">Add</button>
<button onclick="subtract()">Subtract</button>
<div id="answer"></div>

Hope this helps! :)

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71