2

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?

1 Answer 1

2

Try:

var obj = example.split(\"/\"); obj[0];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.