Reputation: 1650
So I have this code in which I am attempting to create a simple calculator:
window.onload = function () {make_buttons ('calc'); }
function make_buttons (id) {
var parent = document.getElementById(id);
var input = document.createElement("input");
input.type = 'text'; input.id = 'inp';
parent.appendChild(input);
for (var i = 0;i < 10; i++){
var btn = document.createElement ("button");
btn.innerHTML = i;
btn.id = i;
parent.appendChild(btn);
(function(index) {btn.onclick = function() {input.value += index;}})(i);
}
var multiply = document.createElement ("button");
multiply.innerHTML = "*";
multiply.id = "*";
parent.appendChild(multiply);
multiply.onclick = function () {input.value += '*';};
var divide = document.createElement ("button");
divide.innerHTML = "/";
divide.id = "/";
parent.appendChild(divide);
divide.onclick = function () {input.value += '/';};
var add = document.createElement ("button");
add.innerHTML = "+";
add.id = "+";
parent.appendChild(add);
add.onclick = function () {input.value += '+';};
var substract = document.createElement ("button");
substract.innerHTML = "-";
substract.id = "-";
parent.appendChild(substract);
substract.onclick = function () {input.value += '-';};
var calc_it = document.createElement ("button");
calc_it.innerHTML = "=";
calc_it.id = "=";
parent.appendChild(calc_it);
calc_it.onclick = function () {calculate ()};
};
function calculate () {
var info = document.getElementById ('inp').value;
console.log(info);
};
So right now when I click the buttons and make the input field have 5 * 5 inside of it for instance - the var info will equal a string "5 * 5". How could I convert this string so that the numbers in the string will be integers and the operators like * or - will also be non string?
Do I need to include some regex code here?
Upvotes: 1
Views: 81
Reputation: 2830
The answer to this question is a difficult one indeed. The obvious and most unpopular answer is an eval, but most likely you are not going to want that.
Basically you will have to code a routine to extract anything you want to use in the expression.
Without using eval or a 3rd party library like 'silentmatts' solution ( below ) you may have to develop your own routine to parse the data.
3rd Party Solution:
Site: http://silentmatt.com/javascript-expression-evaluator/
Git: https://github.com/silentmatt/js-expression-eval
With all of that said, as far as turning a string into a mathematical equation, i personally use eval.
Hope this helps.
Upvotes: 1