Calling replace on string throws EvaluatorException
Asked Answered
G

2

8

I'm trying to adapt this answer to the case of regexp replacement:

  <scriptdef name="propertyregex" language="javascript">
     <attribute name="property"/>
     <attribute name="input"/>
     <attribute name="regexp"/>
     <attribute name="replace"/>
     <![CDATA[
       var input = attributes.get("input");
       var regex = new RegExp(attributes.get("regexp"));
       var replace = attributes.get("replace");
       var res = input.replace(regex, replace);
       project.setProperty(attributes.get("property"), res);
     ]]>
  </scriptdef>

However, executing that code I always get an exception:

javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException:
The choice of Java constructor replace matching JavaScript argument types
(function,java.lang.String) is ambiguous; candidate constructors are: 
    class java.lang.String replace(java.lang.CharSequence,java.lang.CharSequence)
    class java.lang.String replace(char,char)

How can I do regular expression replacement here?

Gap answered 22/10, 2014 at 13:52 Comment(0)
G
11

The problem appears to be that this variable input is of the Java type java.lang.String, which apparently is not the native String type of Rhino. You can avoid this problem by explicitely constructing a JavaScript string:

       var input = new String(attributes.get("input"));
Gap answered 22/10, 2014 at 13:52 Comment(2)
Yes, if you evaluated typeof(attributes.get("input")) you would get "object". More simply, String(attributes.get("input")); would also work. Note that in Nashorn, the JDK 8 JavaScript implementation, native java.lang.String are treated as strings on the JavaScript side.Marginate
This was my problem as well. My JS script under Solr worked on Windows and not under linux. I referred to your answer and it works on both now. As per @DavidP.Caldwell's comment, I changed the JDK on Linux from OpenJDK to Oracle JDK and it works that way as well. Thanks!Deus
A
6

I have found another answer on Alfresco forum.

The problem is, that when the JS code is interpreted, the type of input can't be determined for sure. It could be java.lang.String or Javascripts's string. The proposal from the forum worked for me - just to "cast" input object to JS string like this:

 var res = (input + "").replace(regex, replace);

Note: I've just concatenated the input with empty string.

Hope this helps.

Alver answered 14/9, 2016 at 8:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.