Use JavaScript in ABAP

SAP has provided a class called CL_JAVA_SCRIPT, which can be used to execute JavaScript programs from ABAP. It also enables the data transfer between ABAP and JavaScript.

The ABAP program DEMO_JAVA_SCRIPT_MINI_EDITOR from the Examples Library (transaction ABAPDOCU) is an example of a basic JavaScript Editor, where you can edit, execute, and test JavaScript programs. The program was created using ABAP exclusively and uses the CL_JAVA_SCRIPT class.

Let us see an example of JavaScript in ABAP. We do not have regular expressions (regex or regexp) in SAP 4.7 version. Regular expressions is some sort of wildcards to search a pattern in a text string. We can use the regex or patterns of JavaScript in ABAP to search certain patterns in text strings. Now we use JavaScript in ABAP to find whether a variable contains a valid email address or not.

*&---------------------------------------------------------------------*
*& DATA DECLARATION
*&---------------------------------------------------------------------*
DATA: g_js         TYPE REF TO cl_java_script,
      g_javascript TYPE string,
      g_return     TYPE string.
*&---------------------------------------------------------------------*
*& SELECTION SCREEN
*&---------------------------------------------------------------------*
PARAMETERS: p_email TYPE char20.
*&---------------------------------------------------------------------*
*& START-OF-SELECTION
*&---------------------------------------------------------------------*
START-OF-SELECTION.
* Create JavaScript
  g_js = cl_java_script=>create( ).

* Build JavaScript Code (JavaScript Function to Validate Email)
  CONCATENATE
  'var e = "' p_email '";' INTO g_javascript.
  CONCATENATE g_javascript
  'function validEmail(e) {'
  ' var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;'
  ' return String(e).search (filter) != -1;'
  ' }'
  'validEmail(e);'
  INTO g_javascript SEPARATED BY cl_abap_char_utilities=>cr_lf.

*Get the return value
  g_return = g_js->evaluate( g_javascript ).

*Output
  IF g_js->last_condition_code IS NOT INITIAL.
    WRITE: /'Error : ', g_js->last_error_message.
  ELSE.
    WRITE: /'Email ID ', p_email NO-GAP, ' is Valid : ', g_return.
  ENDIF.

Output

javascript-in-abap-1

javascript-in-abap-2


Be the first to comment

Leave a Reply

Your email address will not be published.


*