How to convert string equation to number in javascript?
Say I have "100*100" or "100x100" how do I evaluate that and convert to a number?
How to convert string equation to number in javascript?
Say I have "100*100" or "100x100" how do I evaluate that and convert to a number?
This will give you the product whether the string is using
*
orx
:If you're sure that the string will always be something like "100*100" you could
eval()
it, although most people will tell you this isn't a good idea on account of the fact that people could pass in malicious code to be eval'd.Otherwise, you'll have to find or write a custom equation parser. In that case, you might want to take a look at the Shunting-yard algorithm, and read up on parsing.
Using
split()
:use parseInt() ,The parseInt() function parses a string and returns an integer.