0

I know there are a lot of people asking about how to convert strings into integers/numbers. But i couldn't find what i was looking for exactly.

I am trying to convert a mathematical problem into a integer. Here's my code:

var str = '1 + 5';
var answer = parseInt(str);
console.log(answer);

OUTPUT: 1

PREFERED OUTPUT: 6

VinceKaj
  • 335
  • 4
  • 13

8 Answers8

3

The simplest answer is to use eval():

var answer = eval('1 + 5');

This will assign 6 to answer.

Of course, eval() allows arbitrary code execution, so if the string is coming from an unknown or untrusted source, this could be an exceptionally dangerous function to use. In that case, you might want to consider parsing the string using something like PegJS

JDB
  • 25,172
  • 5
  • 72
  • 123
2

If you know the source of the scripts, you can use the function eval, be careful with this approach.

var str = '1 + 5';
var answer = eval(str);
console.log(answer);
Ele
  • 33,468
  • 7
  • 37
  • 75
0
var str = '1';
var str2 = '2';
var answer = parseInt(str);
var answer2 = parseInt(str2);
var result = answer+answer2;
console.log(result);
0

'1 + 5' is a complete string, In this case you can break the string and add each element of that array

var str = '1 + 5';
var strArray = str.split('+');
var answer = 0;
strArray.forEach(function(item) {
  answer += parseInt(item, 10)
})
console.log(answer);
brk
  • 48,835
  • 10
  • 56
  • 78
  • "*I am trying to convert a **mathematical problem** into a integer*". I think `1 + 5` was just a simple example. – JDB Feb 20 '18 at 15:11
  • yeah, it was. Plus i am trying to make a script as compact as possible. – VinceKaj Feb 20 '18 at 15:13
0

Here's a prior post that meets your needs using third party libraries.

To explain, both math.js and JavaScript Expression Evaluator can parse through the input you provide them and then calculate what the expression means.

I'd further recommend reading about Lexers and Tokenization to learn for yourself how to break apart expressions, and then experiment with parsing the resulting tokens. This will help with more complex problems as well, such as evaluating expressions of higher level maths or in processing natural language or code for meaning or correctness.

Here's a basic lexer guide for JS

And here's some resources on parsing mathematical expressions

Corvid
  • 13
  • 2
0

Another one with Function constructor.

eq = '1 + 5';
x = new Function('return ' + eq)();
console.log(x)

runMath = x => new Function(`return ${x}`)();

console.log(runMath('1+5'))
console.log(runMath('2*10'))
sabithpocker
  • 15,274
  • 1
  • 42
  • 75
  • thanks, but these 2 examples aren't very compact and something like eval() is good enough for my simple script. – VinceKaj Feb 20 '18 at 15:21
0

so the reason parseInt gives you 1 is because parseInt traverses the string up to the first non number character, and returns the result. It gets tripped up by '+' and just returns 1. Not needed for the answer but an interesting bit to add nonetheless. If you used the Number() constructor instead you would always get NaN. It's for this reason that many people will tell you to use the Number constructor instead but I think there is a case to be made for both.

To accomplish what you want without using eval (which you should probably just never use, see here for info on that) you'll could split the string and parse each item individually. Easiest way to accomplish this is with String.split() and Array.map()

function isNumber(n){
  return !isNaN(n)
}
var t = '1 + 5 + 7'
         //split the string at whitespace into an array
         //this looks like ['1', '+', '5', '+', '7']
var x = t.split(' ') 
         //convert each item to a number, parseInt works here as well
         //this ouputs [1, NaN, 5, NaN, 7]
         .map(Number) 
         //filter out anything that couldn't be converted
         //and you're left with [1,5,7]
         .filter(isNumber) 
         //add each item in the array to get a sum result
         .reduce((a, b) => a + b) 
console.log(x) //outputs 13

This only works if the operator in the string is the same, but you could add a test to see which operator is which, and pass different functions to reduce to get a desired result. If you are interesting mastering javascript I highly encourage reading more about Array.map(), Array.filter(), and Array.reduce(). These functions are extremely useful, and probably my favorite set of functions in the entire language.

Robbie Milejczak
  • 5,664
  • 3
  • 32
  • 65
0

If you didn't want to use eval but you still wanted to keep the code simple for your example, use regex to match the numbers and operator, and use a switch to choose the appropriate case for your operator:

function parser(str) {
  const match = str.match(/(\d+) ([\+\-\*\/]) (\d+)/).slice(1);
  const operator = match.splice(1, 1)[0];
  const numbers = match.map(Number);
  switch(operator) {
    case '+': return numbers[0] + numbers[1];
    case '-': return numbers[0] - numbers[1];
    case '*': return numbers[0] * numbers[1];
    case '/': return numbers[0] / numbers[1];
  }
}

console.log(parser('1 + 2'));
console.log(parser('1 - 2'));
console.log(parser('2 * 2'));
console.log(parser('1 / 21'));
Andy
  • 61,948
  • 13
  • 68
  • 95