This post is part of a series on code snippets. The complete list of posts in the series is available in the document Code Snippets: A Blog Series.
ABAP keyword CONDENSE is useful to remove leading and trailing space characters from a character string, however CONDENSE does not recognize other non-printing whitespace characters such as carriage returns, newlines and horizontal tabs.
Regular expressions give us a useful tool to recognize a wide variety of whitespace characters. The regular expression abbreviation [[:space:]], alternatively written as \s, represents the character set for all non-printing blank characters including space, carriage return, newline and horizontal tab.
The method below removes first trailing then leading whitespace characters from a changing parameter a_string of type string. This code may be used in any ABAP routine but is particularly useful for post-processing of user input in Web Dynpro UI elements such as a TextEdit.
METHOD trim_whitespace.
DATA lv_strlen TYPE i.
DATA lv_char TYPE string.
* Remove trailing whitespace from a_string
DO.
lv_strlen = strlen( a_string ) - 1.
lv_char = a_string+lv_strlen(1).
FIND REGEX '[[:space:]]' IN lv_char.
CASE sy-subrc.
WHEN 0.
SHIFT a_string RIGHT DELETING TRAILING lv_char.
WHEN OTHERS.
EXIT.
ENDCASE.
ENDDO.
* Remove leading whitespace from a_string
DO.
lv_char = a_string+0(1).
FIND REGEX '[[:space:]]' IN lv_char.
CASE sy-subrc.
WHEN 0.
SHIFT a_string LEFT DELETING LEADING lv_char.
WHEN OTHERS.
EXIT.
ENDCASE.
ENDDO.
ENDMETHOD.