-1

I am working on a discord.js and have a found the following problem, I want to convert the users input into a number I am working on a calc bot so the arguments were like 10/2 but I couldn't find a method of converting the string into a number so I thought i would ask, I thought maybe the Number function could work but it didn't and tried using arrays but the join function simply converts it to a string. Anyone know how to solve this?

2 Answers2

4

If you want to avoid the use of eval, you need to parse out the numbers, convert them to numbers, and perform the appropriate operation.

const rx = /(\d+(?:\.\d+)?)\s*([+\-\*\/%])\s*(\d+(?:\.\d+)?)/;

function math(str) {

  const [full, lhs, op, rhs] = rx.exec(str);

  let retval
  switch (op) {
    case '+':
      retval = Number(lhs) + Number(rhs);
      break;
      // etc...
  }

  return retval;

}

console.log("1 + 1 = ", math("1 + 1"));
console.log("1.1 + 1.1 = ", math("1.1+1.1"));

Note that the code above doesn't have any error checking to bail if the string provided isn't a valid operation, or if the numbers aren't really numbers. It's only an example of how you can use a regular expression to get these values, and avoid using the potentially dangerous eval.

TheJim01
  • 8,411
  • 1
  • 30
  • 54
-1

The easiest way to do this is by using eval() which takes a string containing javascript code, evaluates it, and returns the result.

WARNING: this is very dangerous and you can send any javascript code with it and javascript will happily execute it. This would give users of the bot the ability to do any command and basically take remote control of your computer/server. To protect yourself from this you should make sure that the string only contains some allowed characters like this:

const allowedChars = "1234567890/*+-% ";
const input = "2323 + 323";

if (![...input].some(x => !allowedChars.includes(x))) {
    // safe to evaluate
    const result = eval(input);
} else {
    // not safe to execute
}
MrMythical
  • 8,908
  • 2
  • 17
  • 45
Luke_
  • 745
  • 10
  • 23