Hevin Siaton Ebarle
Hevin Siaton Ebarle

Reputation: 1

Javascript: Convert string to computable

please someone help me about my javascript code. I want to convert string to be computable. Example: var string = "34.5 + 30";

the javascript function or code will automatically compute my string value. So the result will be 64.5 with a float or decimal data type.

hope someone can answer my query.

Upvotes: 0

Views: 144

Answers (1)

Nitheesh
Nitheesh

Reputation: 20006

Use eval function.

Reference

The eval() function evaluates JavaScript code represented as a string.

But there is a security issue in this.

Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval(). See Never use eval()!, below.

var myString = "34.5 + 30";
console.log(eval(myString));

Since eval has some security issues, its always adviced not to use it. You could either make use of some custom libraries or implement your own parsing logic.

Please find a small paring logic from my side.

Please note, this evaluates the mathematical expressions linearly. This doesnot works with BODMAS rule or will not evaluate any complex expression. This is to evaluate a mathematical expression that contains only numbers, and basic operators such as +, -, * and /. If you wish to have custom validations you could build on top of this or can implement a solution of your own.

I have added the description as code comment

const myString = "34.5 + 30";

// Regex to split the expression on +, -, *, / and spaces
const isNumeric = /(?=[-+*\/(\s+)])/;

// Valid operators
const operators = ['+', '-', '*', '/'];

// Split the string into array
const expressionArray = myString.split(isNumeric);

// Object to hold the result and the operator while parsing the array generated
const result = { result: 0, operator: '' };

// loop though each node in the array
// If an operator is found, set it to result.operator
// If not an operator, it will be a number
// Check an operator is already existing in result.operator
// If then perform the operation with the current node and result and clear the result.operator
expressionArray.forEach((node) => {
  const trimmedNode = node.trim();
  if (trimmedNode) {
    if (operators.indexOf(trimmedNode) === -1) {
      if (result.operator) {
        switch (result.operator) {
          case '+':
            result.result += Number(node);
            break;
          case '-':
            result.result -= Number(node);
            break;
          case '*':
            result.result *= Number(node);
            break;
          case '/':
            result.result /= Number(node);
            break;
            result.operator = '';
        }
      } else {
        result.result += Number(node);
      }
    } else {
      result.operator = trimmedNode;
    }
  }
});
console.log(result.result);

Upvotes: 1

Related Questions