Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a string into a math operator in javascript [duplicate]

Tags:

javascript

If I've got a string that is a mathematic equation and I want to split it and then calculate it. I know I can use the eval() function to do this, but I'm interested if there's an alternative way to do this - specifically by splitting the strings first. So I've got something like

var myString = "225 + 15 - 10" var newString = myString.split(" "); 

This would turn myString into an array:

["225", "+", "15", "-", "10"]; 

My next task is to turn all the odd-numbered strings into integers, which I think I could use parseInt(); for. My question is, how do I turn the "+" and "-" into actual arithmetic operators? So that at the end I am left with a mathematic expression which I can calculate?

Is this possible?

like image 968
Allen S Avatar asked Oct 25 '12 21:10

Allen S


People also ask

How can I convert a string into a math operator in JavaScript?

To convert a string into a math operator in JavaScript, we use the mathjs package. import { evaluate } from "mathjs"; const myArray = ["225", "+", "15", "-", "10"]; const result = evaluate(myArray.

How do you convert a string to math?

One way would be to simply loop over the string and check hasOwnProperty on your math_it_up object for each element; if it's true, call it with the preceding and succeeding indices in the array as the arguments to the function.

Can we convert string value into number in JavaScript?

To convert a string to an integer parseInt() function is used in javascript. parseInt() function returns Nan( not a number) when the string doesn't contain number. If a string with a number is sent then only that number will be returned as the output.

Which method in JavaScript convert the string into the number?

The parseInt method parses a value as a string and returns the first integer. A radix parameter specifies the number system to use: 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal. If radix is omitted, JavaScript assumes radix 10.


Video Answer


1 Answers

var math_it_up = {     '+': function (x, y) { return x + y },     '-': function (x, y) { return x - y } }​​​​​​​;  math_it_up['+'](1, 2) == 3; 
like image 147
jonvuri Avatar answered Sep 20 '22 04:09

jonvuri