Search code examples
javascriptjavaclojurenashorn

store arbitrary JavaScript code into a string variable


I have a program (written in Clojure) that injects some JS code into a JS function, then evaluates it via Nashorn. I have no control over the code passes (it may contain quotes, simple quotes...).

It looks like this :

;; Clojure
(eval-str (str "print(evaluateCode(\"" s  " \"))"))

// equivalent code in pseudo-js just for those not reading Clojure fluently
evalJS("println(evaluateCode(" + arbitraryJS + "))")

The evaluateCode function is already loaded.

// already loaded in Nashorn
function evaluateCode(code) {
   // do something with the code
   //...
   eval(code);
}

This works fine for simple programs, ex. if arbitraryJS = "var a=123; print(a); return a;".

But as soon as the program contains quotes, it breaks. ex. "var a = 123; print("a is now", a);"

Note : the actual code is there.


Solution

  • In the after end I used the Apache Commons Lang StringUtils since the other solutions did not work. See it here.