How to remove spaces or specified characters from the beginning, end, or all positions of a string and then display it?

Calendar 👁️ 107

In website content operations, we often encounter situations where strings contain unnecessary spaces or specific characters.These seemingly minor issues may affect the display aesthetics, SEO effect, and user experience.For example, a product title may display differently on different devices due to leading and trailing spaces, or a keyword list may be surrounded by additional symbols, affecting search engine recognition.

A security CMS based on Go language development, its powerful Django template engine provides a variety of practical filters that can help us easily handle these strings, ensuring that the final content presented is clean, tidy, and professional.Today, let's delve into how to flexibly use these filters in the Anqi CMS template to remove spaces or specified characters from the beginning, end, or all positions of a string.


Remove leading and trailing spaces/specified characters from a string:trimSeries filter

When we only care about cleaning the ends (beginning and end) of a string,trimSeries filters are our first choice. They can efficiently remove unnecessary leading or trailing characters.

1. Remove all leading and trailing spaces and newline characters from the string:trim

trimThe filter will remove all leading and trailing spaces, tabs, and newline characters if no parameters are specified.This is very useful when handling user input or collecting content from other sources.

For example, we have a title obtained from user input, which may contain extraneous spaces and new lines:

{% set rawString = "   \n\n   欢迎使用安企CMS!\n\n   " %}
<p>原始字符串:'{{ rawString }}'</p>
<p>清理首尾空格和换行符后:'{{ rawString|trim }}'</p>

This code will output: Original string: ‘ Welcome to Anqi CMS!’

‘ After trimming leading and trailing whitespace and newlines: ‘Welcome to Anqi CMS!’

You can see that all the whitespace characters at both ends of the string have been completely removed.

2. Remove the specified characters at the beginning and end of the string:trim(With parameters)

trimThe filter can also accept a string parameter.This parameter defines a character set, the filter checks the beginning and end of the string, and removes characters from the character set until it encounters a character that does not belong to the character set.

For example, a notice title may be automatically prefixed and suffixed by a Markdown or CMS system, and we can clean it up like this:

{% set messyTitle = "### 最新公告 ###" %}
<p>原始标题:'{{ messyTitle }}'</p>
<p>移除首尾'#'号后:'{{ messyTitle|trim:"#" }}'</p>

{% set mixedString = "ABCDEFGHABC" %}
<p>原始字符串:'{{ mixedString }}'</p>
<p>移除首尾'ABC'(字符集)后:'{{ mixedString|trim:"ABC" }}'</p>

The output will be: Original title: '### Latest Announcement ###' Remove the leading and trailing '#' symbols: 'Latest Announcement' Original string: 'ABCDEFGHABC' Remove the leading and trailing 'ABC' (charset) to get: 'DEFGH'

Please note,trim:"ABC"It is not to remove the substring 'ABC', but to treat 'A', 'B', 'C' as a character set.It will first check the beginning, remove 'A', then remove 'B', then remove 'C', and stop when it encounters 'D'.The end is also the same.

3. Remove specified characters from the beginning of the string:trimLeft

If your string only has characters to be cleaned at the beginning, you can usetrimLeftFilter. It can also accept a character set parameter, with the same behavior astrimbut only acts on the left side (beginning) of the string.

{% set dataString = "---重要信息---" %}
<p>原始数据:'{{ dataString }}'</p>
<p>只移除开头'-':'{{ dataString|trimLeft:"-" }}'</p>

Output result: Original data: ‘—important information—’ Remove the prefix ‘-‘: ‘important information—’

4. Remove the specified character at the end of the string: trimRight

Similarly, when you need to clean up characters at the end of a string,trimRightThe filter will be your good helper.

{% set dataString = "---重要信息---" %}
<p>原始数据:'{{ dataString }}'</p>
<p>只移除结尾'-':'{{ dataString|trimRight:"-" }}'</p>

Output result: Original data: ‘—important information—’ Remove the ending ‘-’ to get ‘—important information’


Remove spaces or specified characters from all positions in the string:cutFilter

trimThe series filter only processes the ends of a string, but if we need to remove specific characters from theany position(Not just the beginning and end) of a string,cutThe filter comes into play. It will remove all matching characters from the string.

1. Remove all spaces from the string:cut

When a space is distributed in the middle of a text, it affects typesetting or data processing,cutit can be quickly cleaned up.

{% set spacedText = "安 企 CMS 是 一 款 强 大 的 内 容 管 理 系 统" %}
<p>原始文本:'{{ spacedText }}'</p>
<p>移除所有空格后:'{{ spacedText|cut:" " }}'</p>

Output result: Original text: 'An Qi CMS is a powerful content management system' After removing all spaces: 'AnQiCMS is a powerful content management system'

Remove all specified characters from the string:cut(With parameters)

withtrimsimilar,cutThe filter also accepts a character set parameter. It will traverse the entire string and delete all characters that belong to the character set.

{% set dirtyData = "这是<p>一段</p>包含<>符号的**数据**" %}
<p>原始数据:'{{ dirtyData }}'</p>
<p>移除所有'<', '>', '*', 'p' 字符后:'{{ dirtyData|cut:"<>*p" }}'</p>

Output result: Original data: 'This is

a paragraph

containing < > symbols'dataRemove all ‘ ’, ‘<’, ‘>’, ‘*’, ‘p’ characters from: ‘This is a paragraph containing symbols’data'

Please note,cut:"<>*p"Similarly, it treats '<', '>', '*', and 'p' as a character set rather than matching a specific substring. It will remove all occurrences of these characters one by one from the string.


Combine use: Make content processing more flexible

The AnQi CMS template engine allows multiple filters to be chained together, which means you can first use one filter to process a string, and then pass the processed result to the next filter for secondary processing.

For example, a string may have leading and trailing spaces, as well as some unnecessary symbols inside:

{% set complexString = "  --- 安企CMS 助力内容运营 ---   " %}
<p>原始字符串:'{{ complexString }}'</p>
<p>先移除首尾空格,再移除'-'符号:'{{ complexString|trim|cut:"-" }}'</p>

Output result: Original string: ‘ — AnQi CMS helping content operation — ‘ Remove leading and trailing spaces, then remove the ‘-’ symbol: ‘AnQi CMS helping content operation’

In practical applications, you may need to assign the processed result to a new variable so that it can be used elsewhere in the template, which can be done by{% set %}Tag implementation:

{% set cleanTitle = messyTitle|trim:"#" %}
<p>处理后的标题是:{{ cleanTitle }}</p>

If the content being processed contains HTML tags and you do not want them to be escaped when displayed, you can add at the end|safeFilter. But please ensure that the content source is reliable to avoid XSS attacks.


Summary

By flexibly using the Anqi CMS providedtrim/trimLeft/trimRightandcutFilters, we can easily clean and format strings in website content.Whether it is to remove extra spaces or remove specific characters, these tools can help us present content that is more professional, more readable, and more beneficial for SEO.

Related articles

How to calculate the number of times a certain keyword appears in a string or array and display it?

In the daily work of content operation, we often need to conduct in-depth analysis of website content, one of the common requirements is to understand the frequency of a keyword appearing in a specific string or content block.This is crucial for SEO optimization and also helps us evaluate the relevance and quality of the content.AnQi CMS as an efficient enterprise-level content management system provides us with very convenient built-in tools to solve this problem, that is the powerful `count` filter.

2025-11-08

How to determine if a string, array, or map contains a specific keyword and display the boolean result?

In AnQi CMS template development, we often need to dynamically adjust the display of the page based on the specific attributes or keywords of the content.For example, determine whether an article title contains a certain word, whether a product category is in a certain list, or whether a configuration item exists.The powerful template engine of AnQi CMS provides various filters and operators, which can help us easily implement these judgments and obtain clear boolean (True/False) results.Let's delve deeper into how to implement these flexible judgments in Anqi CMS.### Core Function

2025-11-08

How to display user registration or group details (such as username, level, avatar) on the front page?

In website operation, displaying rich user-related information on the front page is an effective way to enhance user experience and community activity.Whether it is displaying the author's avatar, the user's level, or the username at registration, these personalized details can make the website more vibrant.AnQiCMS as a powerful content management system provides us with very flexible template tags and data call capabilities, making the display of this information easy and simple.### Understand AnQiCMS user and group data In the AnQiCMS backend

2025-11-08

How to automatically convert URLs and email addresses in text to clickable links and display them?

In website content management, we often encounter scenarios where we need to display various links and email addresses in articles or pages.Manually converting this text to clickable HTML links is time-consuming and prone to errors, especially when the amount of content is large, and the workload is惊人的。AnQi CMS fully understands this pain point of users, built-in efficient and intelligent text processing mechanism, can automatically identify and convert URLs and email addresses, greatly improve the efficiency of content publishing and user browsing experience

2025-11-08

How to implement automatic conversion of uploaded images to WebP format to optimize front-end loading and display speed?

In today's content operation, website loading speed is crucial for user experience and search engine rankings.Images are an important part of web content, and their loading performance is often a key factor affecting overall speed.AnQiCMS (AnQiCMS) is well aware of this and provides a convenient image optimization feature, especially converting images uploaded to WebP format automatically, which can significantly improve the display speed of the website's front-end.### WebP format: A speed booster for front-end loading WebP is an image format developed by Google

2025-11-08

How to batch regenerate all content thumbnails to fit the new frontend display size?

When the visual style of a website needs a complete overhaul, or to adapt to the ever-changing size of device displays, we often need to adjust the size of image thumbnails.AnQiCMS (AnQiCMS) fully understands this and provides a convenient and efficient solution for such needs.How to batch regenerate thumbnails for all content in response to adjustments in front-end display dimensions to ensure the aesthetic beauty and loading efficiency of the website, which is a concern for many operators.Why do you need to regenerate the thumbnail? Thumbnails play a crucial role in website operations

2025-11-08

How to set up the website to display specific notification information on the front end when it is in "closed site" status?

The website will always encounter times when it needs to be maintained, upgraded, or temporarily adjusted.At this moment, it is crucial for users to see a friendly and clear prompt instead of a cold error page, which is vital for the image and user experience of the website.Fortunately, AnQiCMS provides a very convenient and flexible "shutdown" function, allowing you to easily manage the maintenance status of the website and display customized notification information to front-end visitors.Next, let's take a look at how to set the "shutdown" status of the website in the AnQiCMS backend

2025-11-08

How to display recommended attributes (such as headlines, recommendations, sliders) in article lists or detail pages?

In AnQi CMS, in order to make your website content more attractive and able to flexibly display articles of different importance levels or display forms, the system provides a "recommended attribute" feature.By cleverly utilizing these properties, you can easily add "headlinesThis guide will take you in-depth to understand how to set and use these recommended properties in AnQiCMS, making your website content management more convenient.

2025-11-08