Calling replace on string throws EvaluatorException

MvG picture MvG · Oct 22, 2014 · Viewed 7.9k times · Source

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?

Answer

MvG picture MvG · Oct 22, 2014

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"));