Tech Tip: Utility method to get the last position of substring
PRODUCT: 4D | VERSION: 19 | PLATFORM: Mac & Win
Published On: August 1, 2022
The method below returns the position of the last occurrence of a substring. If the substring is not found, the method returns 0 (zero).
// Method: lastPosition #DECLARE($target : Text; $source : Text)->$lastPos : Integer var $revSrc; $revTgt : Text var $revPos : Integer If (Count parameters=2) $revSrc:=Split string($source; "").reverse().join("") $revTgt:=Split string($target; "").reverse().join("") $revPos:=Position($revTgt; $revSrc; *) If ($revPos>0) $lastPos:=Length($source)-Length($target)-$revPos+2 End if Else $lastPos:=0 End if |
Examples:
$pos:=lastPosition("oo"; "poolroom") // Returns 6 |
$pos:=lastPosition("tr"; "website") // Returns 0 |