Question

I need to execute a javascript function from within my Rails 4 application. I tried the following with ExecJS (https://github.com/sstephenson/execjs) without any success:

my_js_function = 'function my_function(a){var b=a.split("$");var c="";for(i=0;i<=b.length-1;i++){if(!(i%2)){c+=b[i]}}var b=c.split("");c="";for(i=0;i<=b.length-1;i++){if(i%2){c+=b[i]}}return c}'
compiled_function = ExecJS.compile(my_js_function)
result = compiled_function.call(my_argument)

The original JS function takes an argument (my_argument), which I somehow need to pass on to it. Any help on how this is possible will be much appreciated!

Was it helpful?

Solution

You were close. You should not use call, you should use eval this way:

my_js_function = 'function my_function(a){var b=a.split("$");var c="";for(i=0;i<=b.length-1;i++){if(!(i%2)){c+=b[i]}}var b=c.split("");c="";for(i=0;i<=b.length-1;i++){if(i%2){c+=b[i]}}return c}'
compiled_function = ExecJS.compile(my_js_function)
compiled_function.eval('my_function("heyhey")')
#=> ehy
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top