When working with user input, data cleaning, or text formatting, one of the most common tasks is removing unwanted whitespace. Whether it’s a space accidentally typed before an email address or a newline character left at the end of a copy-paste, these seemingly invisible characters can cause unexpected behavior in your applications.
Fortunately, 4D 21 provides easy-to-use string methods to help: Trim, Trim start, Trim end.
What is Trimming?
Trimming refers to the process of removing whitespace characters, including spaces, tabs, and line breaks, from a string. These characters are usually not visible but can affect string comparisons, storage, and formatting. This behavior follows the ECMAScript standard, which defines which characters are considered whitespace and how they should be removed.
Let’s look at the three key functions:
Trim: the all-around cleaner
Use Trim() when you want to remove all leading and trailing whitespace from a string.
var $cleaned := Trim(" hello world ")
// $cleaned = "hello world"
Trim start: keep the tail
Trim start() only removes leading whitespace. The rest of the string remains unchanged.
var $cleaned := Trim start(" hello world ")
// $cleaned = "hello world "
Trim end: keep the head
And Trim end() does the opposite: it removes trailing whitespace but preserves the beginning of the string.
var $cleaned := Trim end(" hello world ")
// $cleaned = " hello world"
Try it in 4D!
Want to try it out? Just use Trim, Trim start, or Trim end with any text input in your 4D app and watch your strings get neat and tidy.
