KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Utility Method to Escape Strings for URLs
PRODUCT: 4D | VERSION: 19 R | PLATFORM: Mac & Win
Published On: December 5, 2022

URLs have limitations on the characters that can be used. URLs use the ASCII character set and special characters and characters outside of this range must be encoded using percent encoding. Percent encoding replaces the character with a % symble and the two digit hexadecimal of the character code.

The 4D NetKit component has a method to escape strings to be URL safe with the method _urlEscape. Below is the method so that it can be used as a method outside of the component:

#DECLARE($value : Text)->$escaped : Text

var $i; $j; $code; $length : Integer
var $char; $hex : Text
var $shouldEscape : Boolean
var $data : Blob

$length:=Length($value)
For ($i; 1; $length)
   $char:=Substring($value; $i; 1)
   $code:=Character code($char)
   $shouldEscape:=False
  
   Case of
     : ($code=45)
     : ($code=46)
     : ($code>47) & ($code<58)
     : ($code>63) & ($code<91)
     : ($code=95)
     : ($code>96) & ($code<123)
     : ($code=126)
   Else
     $shouldEscape:=True
   End case
  
   If ($shouldEscape)
     CONVERT FROM TEXT($char; "utf-8"; $data)
     For ($j; 0; BLOB size($data)-1)
       $hex:=String($data{$j}; "&x")
       $escaped:=$escaped+"%"+Substring($hex; Length($hex)-1)
     End for
   Else
     $escaped:=$escaped+$char
   End if
End for

Alternatively, If the NetKit component is being used, the method can be set to be accessable from the host database. However it can become inconvient to make this change every time the NetKit component is updated.