How do the `trim`, `trimLeft`, and `trimRight` filters remove spaces or specific characters from the beginning or end of a string?

Calendar 👁️ 76

In website operation and content management, we often encounter the need for string processing, especially in data entry, content display, or API interaction.For example, the user may have mistakenly entered several extra spaces before and after the text box, or some data may have been accompanied by additional specific characters.These seemingly minor issues may affect the layout and aesthetics of the content, and even lead to functional anomalies.

The template engine of AnQi CMS provides a series of powerful filters that help us easily deal with these string cleaning tasks. Today, let's take a detailed look at three very practical filters: trim/trimLeftandtrimRightHow do they help us remove whitespace or specified characters from the beginning or end of a string.

trimFilter: Bidirectional clearing, keeping both ends of the string clean and tidy.

Imagine, you get a piece of text from somewhere, or a user enters some text in a form, and you find that there are unnecessary spaces at both ends of the text, even some special characters. At this point,trimThe filter comes into play. Its main function isto remove all whitespace characters from both ends (beginning and end) of a string.

When used without any parameterstrimWhen the filter is applied, it will default to clearing the characters at the beginning and end of the stringAll Unicode whitespace charactersIncluding spaces, tabs, newlines, and more.

For example, a text segment with leading and trailing spaces:

{{ " 欢迎使用安企CMS " | trim }}

aftertrimAfter processing, the output will be:

欢迎使用安企CMS

ButtrimIts functionality is not limited to that. It can also delete the specifiedcharacter. If you provide a string as a parameter aftertrimit will delete any character contained inthe parameter stringRemove from the beginning and end of the original string until a character that does not belong to the parameter string is encountered.

For example, we want to remove the string.“欢迎使用安企CMS”The words "Welcome" and "CMS" at both ends (note that this is to delete the parameter string that contains theanycharacters):

{{ "欢迎使用安企CMS" | trim:"欢迎CMS" }}

The parameter here is"欢迎CMS"It contains the characters '欢', '迎', 'C', 'M', 'S'.trimIt will start from both ends of the string, removing all these characters until it encounters "shi" or "qi". Therefore, the output will be:

使用安企

We can also assign the processed result to a variable for later use:

{% set original_string = " 欢迎使用安企CMS(AnQiCMS) " %}
{% set cleaned_string = original_string | trim %}
<div>清理空白字符后的结果:{{ cleaned_string }}</div>

{% set original_string_2 = "###重要通知### 这是一个重要消息 ###" %}
{% set cleaned_string_2 = original_string_2 | trim:"#" %}
<div>清理特定字符后的结果:{{ cleaned_string_2 }}</div>

trimLeftFilter: Focus on the left, retaining the original appearance on the right

Sometimes, you might want to clean up the content on the left side (or the beginning) of a string while keeping the right side (the end) unchanged.For example, your data format requires no spaces on the left, but data markers may be retained on the right. In this case,trimLeftThe filter comes into play.

withtrimSimilar, without parameterstrimLeftIt will remove all Unicode whitespace characters from the left of the string:

{{ " 欢迎使用安企CMS " | trimLeft }}

The result will be:

欢迎使用安企CMS 

Notice that the spaces on the right of the string are still retained.

If a parameter is provided,trimLeftIt will remove the characters contained in the parameter string.the parameter stringHowever, it is limited to the left side of the string:

{{ "欢迎使用安企CMS" | trimLeft:"欢迎" }}

The result will be:

使用安企CMS

Here"欢迎"The parameter contains “huan” and “ying”.trimLeftIt will delete “huan” and “ying” from the left until it encounters “shi”.

trimRightFilter: Focus on the right side, the left side is not affected

withtrimLeftRelative, if you only need to clean the content on the right side (tail) of the string, thentrimRightThe filter is your ideal choice.

Without parameterstrimRightWill remove all Unicode whitespace characters from the right of the string:

{{ " 欢迎使用安企CMS " | trimRight }}

The result will be:

 欢迎使用安企CMS

Similarly, the spaces on the left side of the string are retained.

If a parameter is provided,trimRightIt will remove the characters contained in the parameter string.the parameter stringBut limited to the right side of the string:

{{ "欢迎使用安企CMS" | trimRight:"CMS" }}

The result will be:

欢迎使用安企

Here"CMS"The parameter includes "C", "M", "S".trimRightIt will delete these characters from the right until it encounters "QI".

Summary and Application Scenarios

These filters are powerful tools for string cleaning in the Anqin CMS template:

  • trimWhen you need to ensure that there are no redundant contents at either end of a string (whether it is whitespace characters or specific characters), use it.
  • trimLeft: When you only want to normalize the beginning of a string without handling the end.
  • trimRight: When you only want to normalize the end of a string without handling the beginning.

Understand how they handle default blank characters when no parameters are provided, and how they remove characters from the parameter string when parameters are providedanyThe logic of characters, which can help you control the output of content more accurately.Whether it is for cleaning user submitted data, standardizing external interface content, or simply to beautify the page display, these filters can make your content management work more efficient and flexible.


Frequently Asked Questions (FAQ)

Q1:trimWhat is the difference between filter without parameters and with parameters?

A1:The main difference lies in the cleared objects:

  • Without any parametersfor example:{{ value | trim }}), it will remove all Unicode whitespace characters from both endsUnicode whitespace charactersIncluding normal spaces, tabs, and newline characters, etc.
  • When with parametersfor example:{{ value | trim:"abc" }}It will remove the parameters contained in the stringthe parameter stringRemove characters from both ends of the original string. For example,"banana" | trim:"an"It will remove all 'a' and 'n', the result might be"b". It is not to delete the entire substring"an"but to delete the set{'a', 'n'}of any characters.

Q2: How do I remove all spaces from the string, not just the leading and trailing ones?

A2: trimThe series filters only process the beginning and end of strings. If you want to remove all spaces (or specific characters) within the string, you should usereplaceFilter. For example, to remove all spaces, you can write like this:{{ "你好 世界" | replace:" , " }}In which the first parameter is the character you want to replace, the second parameter is the character to be replaced (here it is an empty string).

Q3: Do these filters support Chinese characters?

A3:Yes, the Anqi CMS template engine has good support for Unicode characters (including Chinese characters). Whether it is whitespace characters (such as full-width spaces) or the specific Chinese characters you specify,trim/trimLeftandtrimRightThe filter can correctly identify and process.

Related articles

How to get the thumbnail version of the image according to the image address using the `thumb` filter in the Anqi CMS template?

In website content management, the effective use of images is crucial for improving user experience and page loading speed.AnQiCMS deeply understands this, providing powerful image processing functions, among which the `thumb` filter is a tool that helps us easily obtain the thumbnail version of images.Why thumbnails are so important?Imagine if all the images on your website loaded in their original high-definition large size, how heavy the page would become!

2025-11-08

How does the `stringformat` filter customize the formatted output of any variable like Golang's `fmt.Sprintf()`?

In content operation, the way content is presented often determines the first impression and reading experience of users.Sometimes, simple variable output cannot meet our needs for fine-grained data formatting display, such as retaining fixed decimal places for numbers or adding specific text before output.AnQi CMS provides powerful content rendering capabilities for template developers and content operators, and the `stringformat` filter is a key tool for achieving refined output.It is like the `fmt.Sprintf()` function in Go language, which can format the output of any variable according to custom specifications

2025-11-08

How `split` and `make_list` filters split a string into an array by a specified delimiter or character?

In Anqi CMS template development, flexibly handling string data is an indispensable skill for building dynamic pages.Sometimes, we need to split a long string into a data list using a specified character or string as a delimiter (which is what we commonly call an array);At other times, we may need to process each character of the string independently.AnQi CMS provides two very practical filters: `split` and `make_list`, which can help us easily meet these needs.###

2025-11-08

How to slice a string or array elements within a specified range using the `slice` filter?

The AnQiCMS template engine provides rich filters, giving you great flexibility in displaying content.Among them, the `slice` filter is a very practical tool that can help you accurately extract elements within a specified range of strings or arrays, whether you want to display an article summary, limit the number of images, or handle other data segments, it can be very useful.### The working principle of the `slice` filter The syntax of the `slice` filter is concise and clear: `{{ obj|slice:"from:to" }}`

2025-11-08

How to handle truncation and add an ellipsis when truncating text with `truncatechars` and `truncatewords` filters, including HTML content?

In the increasingly fragmented information consumption era, the way websites present content directly affects user experience.Whether it is the abstract of an article list, the preview of product introduction, or various information stream cards, we need to convey the core information within a limited space while maintaining the page's neatness and uniformity of layout.This introduces the need for text truncation. AnQiCMS, as a fully functional content management system, understands this well and provides us with a powerful text truncation filter, especially its intelligent processing capabilities for HTML content, making content operations more relaxed.

2025-11-08

How to safely truncate text with HTML tags using `truncatechars_html` and `truncatewords_html` filters to prevent structure damage?

In website content operation, we often need to display the summary or part of the content in different scenarios, such as on the list page, search results, or related recommendations.This is when you need to truncate the content.If the content is plain text, a simple character or word cutter can handle the task well.However, when the content is rich in HTML tags, the problem becomes complex: directly cutting may cause the HTML tags to be truncated, thereby destroying the page structure, causing display errors, and even affecting the user experience.

2025-11-08

What are the differences between the `urlencode` and `iriencode` filters in URL parameter encoding, and which scenarios are they applicable to?

In website operation, the construction and processing of URL (Uniform Resource Locator) is a fundamental and critical task.It is crucial to properly encode URLs when dynamically generating links, handling user input as parameters, as it ensures the validity of the links, prevents garbled text, and potential security issues.AnQiCMS provides the `urlencode` and `iriencode` filters to help us better manage special characters in URLs.Although they are all used for encoding, their application scenarios and processing methods are different.

2025-11-08

How `urlize` and `urlizetrunc` filters automatically convert URLs and email addresses in text to clickable hyperlinks?

How to efficiently and beautifully convert text containing URLs and email addresses into clickable hyperlinks when managing website content in AnQi CMS, is a concern for many content operators.Manually adding the `<a>` tag to each URL or email is not only time-consuming and labor-intensive but also prone to errors.Luckily, AnQi CMS provides two very practical template filters——`urlize` and `urlizetrunc`, which can automatically complete this task and greatly improve the efficiency and user experience of content publishing.### `urlize`

2025-11-08