B4J Code Snippet JavaScript Replace with RegEx pattern

Just a bit of language mixing Basic, Java, JavaScript = Example JavaScript Replace with RegEx pattern (Tested with JDK9, B4J v5.9).

Sub Replace Text
B4X:
Sub JSReplace(pattern As String, Target As String, Replacement As String) As String
  Dim Result As String = ""
  Dim joSEM As JavaObject
  Dim script As String = $"function repl() {var re = ${pattern};var str = "${Target}"; return str.replace(re, '${Replacement}');} repl();"$
  joSEM.InitializeNewInstance("javax.script.ScriptEngineManager", Null)
  Try
    Result = joSEM.RunMethodJO("getEngineByName", Array("nashorn")).RunMethod("eval", Array(script))
  Catch
    Log($"[ERROR] - ${LastException.Message}"$)
  End Try
  Return Result
End Sub

Example removing an XML block from HTML string
B4X:
Dim Str as String
Str = $"<xml>This is an XML block.</xml>This is the text after the XML block<BR>..."$
Log(Str)
Str = JSReplace("/<xml.*?>[\S\s]+?<\/xml>/gi", Str, "")
Log(Str)

Output

B4X:
<xml>This is an XML block.</xml>This is the text after the XML block<BR>...
This is the text after the XML block<BR>...
 

rwblinn

Well-Known Member
Licensed User
Longtime User
Thanks for the hint - Intention of the snippet was more to show the usage of JavaScript within a Sub - Replace as an example.
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.
 
Top