I think I would use eval()
, but would first check to make sure the string is a valid mathematical expression, as opposed to something malicious. You could use a regex for the validation.
eval()
also takes additional arguments which you can use to restrict the namespace it operates in for greater security.