In SAP ABAP, you can replace substrings within strings using various methods. Below are the most common approaches:


1. Using REPLACE Statement (Simple Replacement)

The REPLACE statement replaces occurrences of a substring within a string.

Syntax

REPLACE FIRST | ALL OCCURRENCES OF <old_substring>
IN <string>
WITH <new_substring>.

Example

DATA(lv_text) = 'Hello ABAP, ABAP is powerful!'.
REPLACE ALL OCCURRENCES OF 'ABAP' IN lv_text WITH 'SAP'.
WRITE: lv_text. " Output: Hello SAP, SAP is powerful!

2. Using REPLACE with Regular Expressions (REPLACE REGEX)

For more flexible replacements, you can use regular expressions.

Example

DATA(lv_text) = 'Order#123, Order#456, Order#789'.
REPLACE ALL OCCURRENCES OF REGEX '\d+' IN lv_text WITH 'XXX'.
WRITE: lv_text. " Output: Order#XXX, Order#XXX, Order#XXX

3. Using REPLACE in Internal Tables

You can replace text within each row of an internal table.

Example

DATA: lt_table TYPE TABLE OF string,
lv_line TYPE string.
APPEND 'SAP is great!' TO lt_table.
APPEND 'SAP is powerful!' TO lt_table.
LOOP AT lt_table INTO lv_line.
REPLACE 'SAP' IN lv_line WITH 'ABAP'.
WRITE: / lv_line.
ENDLOOP.
" Output:
" ABAP is great!
" ABAP is powerful!

4. Using STRING Function (ABAP 7.40+)

If you’re on a newer version of ABAP, you can use CONV string.

Example

DATA(lv_text) = CONV string( 'Learn SAP, SAP rocks!' ).
lv_text = REPLACE( val = lv_text sub = 'SAP' with = 'ABAP' occ = 'ALL' ).
WRITE: lv_text. " Output: Learn ABAP, ABAP rocks!

5. Using TRANSLATE for Character Replacement

If you want to replace individual characters, use TRANSLATE.

Example

DATA(lv_text) = '123-456-789'.
TRANSLATE lv_text USING '-/'.
WRITE: lv_text. " Output: 123/456/789

Summary Table

MethodWhen to Use
REPLACE ALL OCCURRENCES OFSimple substring replacements
REPLACE REGEXPattern-based replacements
LOOP + REPLACEWhen working with internal tables
REPLACE() functionFor inline expressions in modern ABAP
TRANSLATE USINGCharacter-level replacements