### Run Script

Example running a JavaScript script (requires the javaObject Library).
Its a nice simple way of learning the basics of JavaScript - create a B4J application with a TextArea for writing the JavaScript Code and Run Button with exception handling, showing JavaScript Code error or warnings.
Sub running the Script
' Script - JavaScript
' Return the result of the script or null if no result.
`Sub JSRunScript(Script As String) As String
Dim Result As String
Dim joSEM As JavaObject
joSEM.InitializeNewInstance("javax.script.ScriptEngineManager", Null)
Try
Result = joSEM.RunMethodJO("getEngineByName", Array("nashorn")).RunMethod("eval", Array(Script))
Catch
Result = LastException.Message
Log($"[ERROR] - ${LastException.Message}"$)
End Try
Return Result
End Sub`
Example swapping a name
Dim script As String = $"function swap() {var re = /(\w+)\s(\w+)/;var str = "John Smith";var newstr = str.replace(re, '$2, $1'); return newstr;}; swap();"$
Log(JSRunScript(script))
Output
Smith, John
Hints
If the script should return a value (like a string), then define the script with a function which returns the value and call that function.
Example as from previous:
function swap() {
var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, '$2, $1');
return newstr;
};
swap();
or
function add() {
return 1 + 2;
};
add();

Changed: , Category: JavaScript, File: T6C209M1532.htm, ID: 1532