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?
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.
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.
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.
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.
var math_it_up = { '+': function (x, y) { return x + y }, '-': function (x, y) { return x - y } }; math_it_up['+'](1, 2) == 3;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With