Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

calculate string value in javascript

function calculate(input) {

  var f = {
    add: '+',
    sub: '-',
    div: '/',
    mlt: '*',
    mod: '%',
    exp: '^'
  };

  // Create array for Order of Operation and precedence
  f.ooo = [
    [
      [f.mlt],
      [f.div],
      [f.mod],
      [f.exp]
    ],
    [
      [f.add],
      [f.sub]
    ]
  ];

  input = input.replace(/[^0-9%^*/()-+.]/g, ''); // clean up unnecessary characters

  var output;
  for (var i = 0, n = f.ooo.length; i < n; i++) {

    // Regular Expression to look for operators between floating numbers or integers
    var re = new RegExp('(d+.?d*)([' + f.ooo[i].join('') + '])(d+.?d*)');
    re.lastIndex = 0; // take precautions and reset re starting pos

    // Loop while there is still calculation for level of precedence
    while (re.test(input)) {
      output = _calculate(RegExp.$1, RegExp.$2, RegExp.$3);
      if (isNaN(output) || !isFinite(output)) 
        return output; // exit early if not a number
      input = input.replace(re, output);
    }
  }

  return output;

  function _calculate(a, op, b) {
    a = a * 1;
    b = b * 1;
    switch (op) {
      case f.add:
        return a + b;
        break;
      case f.sub:
        return a - b;
        break;
      case f.div:
        return a / b;
        break;
      case f.mlt:
        return a * b;
        break;
      case f.mod:
        return a % b;
        break;
      case f.exp:
        return Math.pow(a, b);
        break;
      default:
        null;
    }
  }
}
Comment

calculate string value in javascript

<div>
  <label for="input">Equation: </label>
  <input type="text" id="input" value="12/5*9+9.4*2-1" />
  <input type="button" 
         value="calculate" 
         onclick="getElementById('result').value = calculate(getElementById('input').value)" />
</div>

<div>
  <label for="result">Result: </label>
  <input type="text" id="result" />
</div>
Comment

calculate string value in javascript

let res2 = (new Function('return '+str)())
Comment

calculate string value in javascript

label {
  display: inline-block;
  width: 4em;
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: death calculator by date of birth make in java 
Javascript :: V2271823410017645510 
Javascript :: rxjs que recibe como parametro un observable 
Javascript :: javascript match image attribute value 
Javascript :: validator.js github 
Javascript :: javascript copy array map 
Javascript :: heroku node js h21 backend connection refused 
Javascript :: cannot create an instance of an abstract class httphandler angular 
Javascript :: juqey unbind click 
Javascript :: toastr js dont fade out 
Javascript :: how to filter data from mongodb date in reactjs 
Javascript :: is nodejs code visible client side 
Javascript :: how many characters can fit in 1 line of div 
Javascript :: javascript see if chrome is in dark mode 
Javascript :: renderIndicator example react responsive carousel 
Javascript :: chromepicker react-color not working 
Javascript :: generate random hsl color values 
Javascript :: enum mongoose doesnt trigger error 
Javascript :: how to merge duplicate value in array of object site:stackoverflow.com 
Javascript :: array.of 
Javascript :: solutions on Multiply - Declaring a Function as a Variable 
Javascript :: fetch an webpage and parse js 
Javascript :: check string ifhas character in jquery 
Javascript :: getx remove all previous routes 
Javascript :: vanilla js game loop 
Javascript :: replace all commas in string javascript 
Javascript :: render one canvas over another 
Javascript :: vuex get data in mounted 
Javascript :: signin with google widget floating automatically 
Javascript :: check the constructor property to find out if an object is an Array (contains the word "Array"): 
ADD CONTENT
Topic
Content
Source link
Name
3+5 =