B4J Code Snippet JavaScript Replace with RegEx pattern

Discussion in 'B4J Code Snippets' started by rwblinn, Oct 11, 2017.

  1. rwblinn

    rwblinn Well-Known Member Licensed User

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

    Sub Replace Text
    Code:
    Sub JSReplace(pattern As String, Target As String, Replacement As StringAs 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
    Code:
    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

    Code:
    <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>...
     
    inakigarm likes this.
  2. Erel

    Erel Administrator Staff Member Licensed User

    Note that there is a built-in Regex.Replace method:
    Code:
    Dim Str As String = $"<xml>This is an XML block.</xml>This is the text after the XML block<BR>..."$
    Log(Regex.Replace("<xml>[\S\s]+?</xml>", Str, ""))
     
  3. rwblinn

    rwblinn Well-Known Member Licensed 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.
     
    Erel likes this.
Loading...