Question

I want to use ScriptEngine of Java but I have some trouble with javascript split function like below:

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    Bindings bindings = engine.createBindings();
    bindings.put("example", "123/456/789");

    String s1 = "var obj = example.split(\"/\"); print(obj[0]);";

    Object result = engine.eval(s1, bindings);

    System.out.println(result);

when I evaluate the script; this code prints "123null" because result is null. When I tried return statement instead of print like this:

    String s1 = "var obj = example.split(\"/\"); return obj[0];";

throws an exception:

Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException: invalid return (#1) in at line number 1

So how should I get the value of first index from this splitted native array?

Was it helpful?

Solution

Try:

var obj = example.split(\"/\"); obj[0];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top