Please disable your adblock and script blockers to view this page
 

Javascript to Evaluate a String as Mathematical Expression

Introduction: In this article I am going to explain how to evaluate/ calculate a string expression as a mathematical expression using jquery/Javascript’s eval() function.
Javascript to Evaluate a String as Mathematical Expression


Description: The eval() function evaluates or executes an argument.
If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.

Syntax: eval(string)

Implementation: Let’s understand by an example.

<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
        function EvaluateExpression() {
            var expression = $('#txtExpression').val().trim();

            if (expression != '') {
                try {
                    var result = eval(expression);
                    $('#spnMessage').html('Result is : ' + result);
                }
                catch (e) {
                    $('#spnMessage').html('Expression in invalid.');
                }
            }
            else {
                $('#spnMessage').html('Please enter expression.');
            }
        }
    </script>
</head>
<body>
    <input type="text" id="txtExpression" />
    <button type="button" onclick="EvaluateExpression();">Evaluate</button><br /><br />
    <span id="spnMessage"></span> 
</body>
</html>

Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates. 
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. ConversionConversion EmoticonEmoticon