Search code examples
c#jint

How do I parse javascript code in Jint interpreter?


I want to make sure javascript code is valid syntax:

string test = " var i = 0; ";
Jint.Engine ScrptingEngine = new Jint.Engine();
bool result = ScrptingEngine.Parse(test);

Solution

  • You can use the Execute() method to "parse" your JavaScript and the GetValue() method to retrieve the value and then assert that it works as intended.

    string test = " var i = 0; ";
    Jint.Engine ScrptingEngine = new Jint.Engine();
    var result = ScrptingEngine.Execute(test).GetValue("i");
    Assert.AreEqual(0, result);
    

    In addition, the Execute method will also throw a JavaScriptException if the JavaScript is invalid:

    try
    {
        ScrptingEngine.Execute("xx = ss == esfx = fuct()"); 
    }
    catch(JavaScriptException ex) {}