Search code examples
javascriptjavanashorn

Java Nashhorn New Line


I have a problem with the Java Nashhorn engine. New Lines (\n) do not working.

Example:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("print('test \n')");

This is the error output:

javax.script.ScriptException: <eval>:1:12 Missing close quote

Thanks for helping


Solution

  • You need to escape the \. Otherwise the effective javascript looks like:

    print('test 
    ')
    

    Which is incorrect.

    Use this:

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    engine.eval("print('test \\n')");