0

I'm making a system that will use a calculator, however, at any given time the user must click on a word, and that word needs to have a value, for example 20. see the example of how mathematical formula works:

car = 20;
2 + (car + 1);

the result of this formula is 23

these words and values ​​comes from database

Anyone know how to do this in javascript?

the javascript code:

function addChar(input, character) {
    if (input.value == null || input.value == "0"){
        input.value = character;
    }
    else{
        input.value += character;
    }
}
function cos(form) {
    form.display.value = Math.cos(form.display.value);
}
function sin(form) {
    form.display.value = Math.sin(form.display.value);
}
function tan(form) {
    form.display.value = Math.tan(form.display.value);
}
function sqrt(form) {
    form.display.value = Math.sqrt(form.display.value);
}
function ln(form) {
    form.display.value = Math.log(form.display.value);
}
function exp(form) {
    form.display.value = Math.exp(form.display.value);
}
function sqrt(form) {
    form.display.value = Math.sqrt(form.display.value);
}
function deleteChar(input) {
    input.value = input.value.substring(0, input.value.length - 1)
}
function changeSign(input) {
    if (input.value.substring(0, 1) == "-"){
        input.value = input.value.substring(1, input.value.length);
    }
    else{
        input.value = "-" + input.value
    }
}
function compute(form) {
    form.display.value = eval(form.display.value)
}
function square(form) {
    form.display.value = eval(form.display.value) *
            eval(form.display.value)
}
Daniel Swater
  • 237
  • 1
  • 6
  • 19

1 Answers1

0
var data = {"car":20};
var formula = " 2 + (%car% + 1)";
for (var index in data){
    formula = formula.replace(new RegExp("%"+index+"%","g"),data[index]);
}
alert(eval(formula));

use prefix and suffix for ignoring partial match word replacing error. i used %

Ingreatway
  • 145
  • 8
  • good answer but is really needed to use `%`? check mine please and tell me your opinion. – Sina R. Jun 03 '13 at 13:14
  • but how do I add a string and the value in the variable data? – Daniel Swater Jun 03 '13 at 13:55
  • use prefix and suffix for ignoring partial match word replacing error. i used %. if u using without % then if u have two variables like "car" and "carvalue" when u replacing value for car. carvalue also get replace. like 20value (carvalue). so i added % – Ingreatway Jun 04 '13 at 13:09