KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Utility method to find and replace string in 4D Write Pro
PRODUCT: 4D | VERSION: 18 R | PLATFORM: Mac & Win
Published On: June 14, 2021

While 4D v19 has included a new find and replace string method, the operation still must be created manually in previous versions. Using the utility method below, this method will find a searched string and replace it with a new string within a 4D Write Pro area.

// ----------------------------------------------------
// Method: WP_findAndReplace
// Description
// Finds and replaces string in 4D Write Pro area
// Parameters
// $1 - WPArea
// $2 - String to find
// $3 - String that replaces found text
// ----------------------------------------------------

C_OBJECT($1; $WPArea_o)
C_TEXT($2; $searched_t)
C_TEXT($3; $replaced_t)

C_TEXT($WPText_t)
C_COLLECTION($found_c)
C_OBJECT($found_o)
C_LONGINT($pos_l)
C_OBJECT($range_o)
C_LONGINT($i)

$WPArea_o:=$1
$searched_t:=$2
$replaced_t:=$3

$found_c:=New collection

// Freeze all expressions to plain text
WP FREEZE FORMULAS($WPArea_o)

// Convert WParea text to plain text
$WPText_t:=WP Get text(WParea)

// Find string in WP text area
Repeat
   $pos_l:=Position($searched_t; $WPText_t; $pos_l)
   If ($pos_l#0)
   $found_o:=New object
   $found_o.startPos:=$pos_l
   $found_o.endPos:=$pos_l+Length($searched_t)
   $found_c.push($found_o)
  
   $pos_l:=$found_o.endPos
   End if
Until ($pos_l=0)

// Replace string
For ($i; $found_c.length-1; 0; -1)
   $found_o:=$found_c[$i]
   $range_o:=WP Text range($WPArea_o; $found_o.startPos; $found_o.endPos)
   WP SET TEXT($range_o; $replaced_t; wk replace)
End for


To call the utility method, simply pass in the 4D Write Pro area object, string to find, and new replacement string. For example, this call will replace all "Lorem Ipsum" with "REPLACEMENT TEXT".

WP_findAndReplace(WParea; "Lorem Ipsum"; "REPLACEMENT TEXT")