How to flexibly remove spaces or specified characters from the beginning or end of a string in AnQi CMS using `trim`, `trimLeft`, and `trimRight` filters?

Calendar 👁️ 74

During website content operation, we often encounter the need for string processing, such as cleaning user input, uniform display format, or optimizing search engine inclusion (SEO) and so on. AnQiCMS (AnQiCMS) powerful template engine provides a variety of practical filters, among whichtrim/trimLeftandtrimRightThese three filters are the powerful assistants we use to flexibly remove extra spaces or specified characters from the beginning and end of strings or in specific directions.

trimFilter: Bidirectional trimming, accurately removes characters from the beginning and end.

trimThe filter, as the name implies, is mainly used to trim the ends of strings. Its core function is to remove unnecessary characters from the beginning and end of the string.

Basic usage: Remove leading and trailing spaces.WhentrimThe filter, when not provided with any parameters, will default to removing all whitespace from both ends of the string (including spaces, tabs, and newlines, etc.).This is especially useful when dealing with data from different sources, as it ensures the cleanliness of the displayed content.

For example, if a string variablemessagehas a value of" 欢迎使用安企CMS "We can use it like this:

{{ "  欢迎使用安企CMS  "|trim }}
{# 显示结果:欢迎使用安企CMS #}

Advanced usage: Remove specified character set trimThe filter is stronger in that it allows you to specify a 'character set' to delete.The 'character set' does not refer to deleting a complete word, but rather to each individual character in the string you provide to the filter.trimIt will check if the original string starts and ends with any characters from this character set and remove them in a loop until it encounters a character not in the character set.

For example, if your string is"--- 安企CMS ---"and you want to remove the characters from both ends"-"and" "characters:

{{ "--- 安企CMS ---"|trim:" -" }}
{# 显示结果:安企CMS #}

In this example," -"Provided as a character set. The filter will start from both ends of the string, removing all occurrences of"-"or" "until it encounters a non"-"Also not" "character.

You can also store the processing result in a variable for later use, for example:

{% set rawString = "### 安企CMS文档 ###" %}
{% set cleanedString = rawString|trim:"# " %}
{{ cleanedString }}
{# 显示结果:安企CMS文档 #}

trimLeftFilter: Focus on cleaning the beginning of the string.

If you only want to handle the beginning part of a string,trimLeftthe filter is your ideal choice. It works in a similar way,trimbut only acts on the left side of the string.

Basic usage: Remove leading spacesWhen used without parameters,trimLeftit will remove all leading spaces from the string:

{{ "   系统公告:安企CMS更新了!"|trimLeft }}
{# 显示结果:系统公告:安企CMS更新了! #}

Advanced usage: Remove specified leading character setwithtrimSame,trimLeftIt also accepts a character set as a parameter. It will start from the beginning of the string and remove all characters that belong to the character set until it encounters the first character that does not belong to the character set:

{{ "【置顶】安企CMS使用教程"|trimLeft:"【置顶】" }}
{# 显示结果:安企CMS使用教程 #}

In this example,"【置顶】"Provided as a character set. The filter will remove all characters encountered///that appear at the beginning of the string

trimRightFilter: Refine the end of the string

withtrimLeftCorrespondingly,trimRightThe filter focuses on processing the end of the string. It starts from the right side of the string and performs deletion operations.

Basic usage: Remove trailing spaceswhen no parameters are provided,trimRightIt will remove all trailing spaces at the end of the string:

{{ "安企CMS:高效内容管理工具   "|trimRight }}
{# 显示结果:安企CMS:高效内容管理工具 #}

Advanced usage: Remove specified trailing character set trimRightIt can also accept a character set parameter. It will start from the end of the string and remove all characters that belong to the character set, until it encounters the first character that does not belong to the character set:

{{ "联系我们(客服)"|trimRight:"(客服)" }}
{# 显示结果:联系我们 #}

Here, "(客服)"Is considered a character set.trimRightWill remove all characters encountered at the end of the///string if they appear at the end.

Actual application scenarios and tips

ThesetrimFilters are widely used in content management:

  • Data cleaning:When importing content from a database or other system, it is often encountered that the field values contain unnecessary spaces or special symbols.Use these filters to quickly clean the data, ensuring a tidy and standardized frontend display.
  • User input validation and formatting:After the user submits a form (such as comments, reviews, search keywords), you can usetrimClean leading and trailing spaces to avoid match failure or display异常 due to extra spaces.
  • SEO optimization:Ensure page title, keywords, description, etc.metaInformation is not affected by extra spaces or characters in search engine parsing.Although Anqi CMS has made many optimizations in the background, manual trimming may still be required in some custom output scenarios.
  • Unified content display style: Some articles or product names may have special prefixes or suffixes, throughtrimLeftortrimRightYou can unify the display style of the front-end without modifying the original content.

When using these filters, please always remember that when you provide关键词parameters, the filter is based onthe character setfor deletion, which means it will remove any characters from the string that match关键词Matching the first and last character of any character, rather than deleting a complete "word" or "phrase".


Frequently Asked Questions (FAQ)

  1. Q:trimin the filter关键词Are you deleting a complete word or each character in the keyword?A: Here is the关键词parameter refers to athe character set.trim(includingtrimLeftandtrimRightIt will check if the string at the beginning (or in one direction) contains any character from the set and remove it. It will not remove the characters you provide.关键词As a complete phrase to match and delete. For example,"AnQiCMS"|trim:"CMS"It will delete all occurrences ofC/M/Scharacters, not just deleteCMSthis word.

  2. Q: I want to delete a specific complete word from the beginning of a string, for example【新】,trimLeftCan it be done?A:trimLeftIt is based on character set deletion, if your string is【新】安企CMS,trimLeft:"【新】"It can indeed be processed as安企CMS. But this is because//These three characters exactly form the phrase you need to delete. If there are other characters within the phrase, or if the phrase itself is not composed of the characters from the set you provided,trimLeftIt cannot be used as a tool to delete specific phrases. For the need to delete specific complete phrases, you may need to combinereplacefilters or more complex logic to achieve this.

  3. Q: If the string itself does not have leading and trailing spaces or specified characters, what impact will the filter have?trimWhat impact will the filter have?A: If the string itself does not contain leading and trailing spaces or specified characters, usetrim/trimLeftortrimRightthe filter will not affect the string

Related articles

How to implement batch string replacement with the `replace` filter in AnQi CMS, especially when performing SEO keyword optimization?

AnQiCMS, with its flexible and efficient features, has become a powerful assistant for many content operators to improve their website performance.In website operation, especially when performing SEO keyword optimization, the accuracy and timeliness of content are crucial.Today, let's delve deeply into a seemingly simple yet powerful tool in Anqi CMS—the `replace` filter, and how to巧妙运用it巧妙运用it effectively to achieve batch replacement of strings, thereby making your SEO keyword optimization work twice as effective.### One

2025-11-08

How to use the `repeat` filter in Anqi CMS template to quickly generate repeated placeholders or decorative strings?

In AnQi CMS template design, flexibly using various filters (Filter) is the key to improving template performance and development efficiency.Among them, the `repeat` filter provides a very convenient solution for quickly generating repetitive placeholders or decorative strings with its concise characteristics.`repeat` filter, as the name implies, is mainly used to repeat a specified string or variable content according to the number of times set.

2025-11-08

How to use the `stringformat` filter in Anqi CMS templates combined with `if` tags to output different string descriptions based on the value size?

In website operation, we often encounter the need to dynamically adjust the display content of the page based on data.For example, a product page may display "Sufficient stock", "Tight stock" or "Temporarily out of stock" based on the inventory quantity; a user points page may display "Regular member", "Senior member" or "VIP member" based on the points level.

2025-11-08

Does the `thumb` filter in AnQi CMS support specifying the width and height of the thumbnail, or only fetching the cropped URL?

When using Anqi CMS for website content management, we often need to handle images, especially thumbnails for articles or products.This is when the `thumb` filter comes into play.It can help us easily generate and obtain the thumbnail address from a complete image address.However, many friends may be curious, does this `thumb` filter support specifying the width and height of thumbnails directly when used?Or is it just returning a cropped image URL?

2025-11-08

The `render` filter of AnQi CMS can render which specific string formats into HTML output besides Markdown?

In the daily use of the content management system, we often need to display the stored plain text content in rich HTML form to users.AnQiCMS (AnQiCMS) provides powerful template rendering capabilities, where the `render` filter is one of the key tools for handling such requirements.Many users may already know that it can convert Markdown-formatted text to HTML, so what specific formats can this `render` filter handle besides Markdown?

2025-11-08

How to display article title and content in AnQiCMS template?

In Anqi CMS, whether it is to display the detailed content of a single article or present the article title and summary on the list page, it is all due to its flexible and easy-to-understand template tag system.AnQiCMS uses a syntax similar to the Django template engine, making content calls intuitive and efficient.

2025-11-08

How to customize the URL structure of the article detail page in AnQiCMS for optimized display?

In website operation, a clear and meaningful URL structure not only helps search engines better understand and capture your content, but also significantly improves the browsing experience of users.AnQiCMS knows this and therefore provides flexible and powerful features that allow you to easily customize the URL structure of the article detail page. Let's take a deeper look at how AnQiCMS can help you achieve this goal, creating a more advantageous URL for your website.Why is it important to customize URL structure?Before delving into the features of AnQiCMS

2025-11-08

How to use AnQiCMS content model to customize fields and display them on the front end?

In website operation, we often encounter such situations: the standard 'article' or 'product' content type cannot fully meet our unique business needs.For example, you may need to post "real estate information", which requires special fields such as "house type", "area", "orientation", etc.Or you are running a "recruitment platform" and need "job title", "location", "salary range", and "skills required" and so on.At this moment, the flexible content model and custom field function of AnQiCMS are particularly important, as they can help us create a content structure that perfectly fits the business

2025-11-08